<template>
    <view class="container">
        <view class="bg_img">
            <image class="img_val"
                   src="../static/room1/bg@2x.png"
                   mode="aspectFill"></image>
        </view>
        <!-- 礼物动画对象数组 -->
        <image class="give_animation_box"
               v-for="(item,index) in giveAnimationList"
               :key="index"
               :src="item.giftUrl"
               @load="imageLoad"
               :animation="giveAnimationList2[index]"
               mode="" />
        <com-nav-bar :navColor="'none'">
            <template>
                <view class="header">
                    <view class="roomMsg">
                        <view class="goBack u-flex u-row-center u-col-center"
                              @click="handleGoBack">
                            <image src="../static/room1/qert.png"></image>
                        </view>
                        <view class="msg">
                            <view class="title">{{roomInfo.title}}</view>
                            <view class="idAndType">
                                <text>ID:{{ownerErbanNo}}</text>
                                <text>【{{roomInfo.roomTag}}】</text>
                            </view>
                        </view>
                        <view class="connect"
                              v-if="!isFavor && currentInfo.role != 3"
                              @click="handleConnect">收藏</view>
                        <view class="connect"
                              v-if="isFavor && currentInfo.role != 3"
                              @click="disHandleConnect">已收藏</view>
                    </view>
                </view>
            </template>
        </com-nav-bar>

        <view class="hot">
            <view class="_icon">
                <image class="img_val"
                       src='../static/room1/hot.png'></image>
            </view>
            <view class="hotNum">
                <image src='../static/room1/rm.png'></image>
                <text>3100</text>
            </view>
        </view>
        <view class="manager">
            <view v-for="(item) in micQueue.slice(0,1)"
                  :key="item.position"
                  class="eachUser">

                <view class="main"
                      @click="handleClickMic(item)"
                      id="userPosition-1">
                    <view class="ornaments"
                          v-if="item.uid && item.volume > 0">
                        <image src="../static/room1/voicing.png"
                               class="img_val"></image>
                    </view>
                    <view class="mute">
                        <image v-show="item.micState == 1"
                               src="../static/room1/close.jpg"></image>
                    </view>
                    <view>
                        <template>
                            <image class="userphoto"
                                   v-if="item.uid"
                                   :src="micQueue.find(ele => ele.uid == item.uid).avatar">
                            </image>
                            <image class="userphoto"
                                   src='../static/room1/suomai.png'
                                   v-else-if="item.posState == '1'">
                            </image>
                            <image class="userphoto"
                                   src='../static/room1/open.png'
                                   v-else-if="item.posState == '0'">
                            </image>
                        </template>
                    </view>

                </view>
                <view class='userMsg'>

                    <text>
                        <text class="outhPic"
                              v-if="item.role > 0 && item.uid ">{{renderOuth(item.role)}}</text>
                        {{ item.uid ?   micQueue.find(ele => ele.uid == item.uid).nick : '主持位'}}
                    </text>
                    <view class="giftNum"
                          v-if="roomInfo.showGiftValue">
                        <image src='../static/room1/rm.png'></image>
                        <text>{{giftValueVos.find((ele) => ele.uid == item.uid) ? giftValueVos.find((ele) => ele.uid == item.uid).giftValue : 0 }}</text>
                    </view>
                </view>

            </view>
        </view>

        <view class="audioUsers">
            <view v-for="(item , index) in micQueue.slice(1)"
                  :key="item.position"
                  class="eachUser">
                <view class="main"
                      :id="`userPosition${index}`">
                    <view class="ornaments"
                          v-if="item.uid && item.volume > 0">
                        <image src="../static/room1/voicing.png"
                               class="img_val"></image>
                    </view>
                    <view class="mute">
                        <image v-show="item.micState == 1"
                               src="../static/room1/close.jpg"></image>
                    </view>
                    <view @click="handleClickMic(item)">
                        <template>
                            <image class="userphoto"
                                   v-if="item.uid"
                                   :src="micQueue.find(ele => ele.uid == item.uid).avatar"></image>
                            <image class="userphoto"
                                   src='../static/room1/suomai.png'
                                   v-else-if="item.posState == '1'">
                            </image>
                            <image class="userphoto"
                                   :src="index == 7 ? '../static/room1/boss.png' : '../static/room1/open.png' "
                                   v-else-if="item.posState == '0'">
                            </image>
                        </template>

                    </view>

                </view>
                <view class="userMsg">
                    <text>
                        <text class="outhPic"
                              v-if="item.role > 0 && item.uid ">{{renderOuth(item.role)}}</text>
                        {{ Number(item.position) + 1  + (item.uid ?   micQueue.find(ele => ele.uid == item.uid).nick : '号麦位')}}
                    </text>
                    <view class="giftNum"
                          v-if="roomInfo.showGiftValue">
                        <image src='../static/room1/rm.png'></image>
                        <text>{{ giftValueVos.find((ele) => ele.uid == item.uid) ? giftValueVos.find((ele) => ele.uid == item.uid).giftValue : 0 }}</text>
                    </view>
                </view>
            </view>
        </view>
        <view class="chatBox">
            <swiper class="swiper_box"
                    indicator-dots
                    autoplay
                    :interval="3000"
                    :duration="300">
                <template v-for="(active , index) in activityList">
                    <swiper-item v-if="active.skipType == 3"
                                 :key="index">
                        <image class="swiper_img"
                               :src="active.alertWinPic"
                               @click="goActiveWebView(active)"
                               mode="" />
                    </swiper-item>
                </template>
            </swiper>
            <scroll-view scroll-y="true"
                         class="scroll-Y "
                         v-show="!roomInfo.isCloseScreen"
                         :scroll-top="scrollTop">
                <view v-for="(msg , index) in chatMsgArr"
                      :key="index">
                    <template>
                        <view class="tip_text"
                              v-if="index <= 1">{{ msg }}</view>
                        <view class="notification"
                              v-if="renderMessageType(msg) == 'memberEnter' ">
                            <image :v-if="JSON.parse(msg.fromCustom)[msg.from].wealthLarge"
                                   :src="JSON.parse(msg.fromCustom)[msg.from].wealthLarge"></image>
                            <image :v-if="JSON.parse(msg.fromCustom)[msg.from].charmLarge"
                                   :src="JSON.parse(msg.fromCustom)[msg.from].charmLarge"></image>
                            <!-- 铭牌 -->
                            <image :v-if="JSON.parse(msg.fromCustom)[msg.from].nameplateUrlAndText"
                                   :src="JSON.parse(msg.fromCustom)[msg.from].nameplateUrlAndText"></image>
                            <view class="notifiMsg">
                                <text class="nick">{{msg.attach.fromNick}}</text>
                                <text class="inroom">进入房间</text>
                            </view>
                            <view class="wel">欢迎</view>
                        </view>
                        <view class="commonMsg"
                              v-else-if="renderMessageType(msg) == 'text' ">
                            <view class="user">
                                <view class="pic">
                                    <image :src="msg.fromAvatar"></image>
                                    <view v-if="msg.custom">
                                        <view v-if="JSON.parse(msg.custom).roomMemberType == 1"
                                              class="outh">房</view>
                                        <view v-if="JSON.parse(msg.custom).roomMemberType == 2"
                                              class="outh">管理</view>
                                    </view>
                                    <view v-if="!msg.custom">
                                        <view v-if="currentInfo.role == 1 ||  currentInfo.role == 2"
                                              class="outh">管</view>
                                        <view v-if="currentInfo.role == 3"
                                              class="outh">房</view>
                                    </view>

                                </view>
                                <view class="right">
                                    <text class="nick">{{msg.fromNick}}</text>
                                    <view class="brage">
                                        <image :v-if="JSON.parse(msg.fromCustom)[msg.from].wealthLarge"
                                               :src="JSON.parse(msg.fromCustom)[msg.from].wealthLarge"></image>
                                        <image :v-if="JSON.parse(msg.fromCustom)[msg.from].charmLarge"
                                               :src="JSON.parse(msg.fromCustom)[msg.from].charmLarge"></image>
                                        <!-- 铭牌 -->
                                        <image :v-if="JSON.parse(msg.fromCustom)[msg.from].nameplateUrlAndText"
                                               :src="JSON.parse(msg.fromCustom)[msg.from].nameplateUrlAndText"></image>
                                    </view>
                                </view>
                            </view>
                            <view class="msgText">
                                {{msg.text}}
                            </view>
                        </view>
                        <view v-else-if="renderMessageType(msg) == 'custom' "
                              class="customMsg">
                            <!-- {{roomParamsState.owner == 'true' ? JSON.parse(msg.content).data.tips : JSON.parse(msg.content).data.targetToast}} -->
                            {{JSON.parse(msg.content).data.tips}}
                        </view>
                        <view class="gift_give u-flex u-flex-wrap u-col-center"
                              v-else-if="renderMessageType(msg) == 'giftGive' ">
                            <!-- 福袋全麦打赏 -->
                            <view v-if="JSON.parse(msg.content).data.luckyGiftList && JSON.parse(msg.content).second == 122"
                                  class="u-flex u-col-center u-flex-wrap">
                                <span class="nickname">{{ JSON.parse(msg.content).data.luckyGiftList[0].nick }}</span>
                                <span class="give_type_text">{{ '全麦打赏' }}</span>
                                <span class="blessing_bag">{{ `${JSON.parse(msg.content).data.luckyGiftList[0].sendGiftName}，爆出了` }}</span>
                                <view class="u-flex u-col-center u-flex-wrap"
                                      v-for="(item , index) in JSON.parse(msg.content).data.luckyGiftList"
                                      :key="index">
                                    <span class="blessing_bag">{{ ` 价值${item.goldPrice}金币的礼物`}}</span>
                                    <image class="gift_img"
                                           v-if="item"
                                           :src="item.giftUrl"
                                           mode="" />
                                    <span class="blessing_bag">{{ ` 给${item.targetNick }` }}</span>；
                                </view>
                            </view>
                            <!-- 福袋送礼 -->
                            <view v-else-if="JSON.parse(msg.content).second == 33"
                                  class="u-flex u-col-center u-flex-wrap">
                                <span class="nickname">{{ JSON.parse(msg.content).data.nick }}</span>
                                <span class="give_type_text">{{ '打赏' }}</span>
                                <span class="blessing_bag">{{ `${JSON.parse(msg.content).data.sendGiftName}，爆出了 价值${JSON.parse(msg.content).data.gift.goldPrice}金币的礼物`}}</span>
                                <image class="gift_img"
                                       v-if="JSON.parse(msg.content).data.gift"
                                       :src="JSON.parse(msg.content).data.gift.giftUrl"
                                       mode="" />
                                <span class="blessing_bag">{{ ` 给${JSON.parse(msg.content).data.targetNick }` }}</span>；
                            </view>
                            <view v-else-if="JSON.parse(msg.content).second == 38"
                                  class="u-flex u-col-center u-flex-wrap">
                                <!-- 特权 -->
                            </view>
                            <view v-else-if="JSON.parse(msg.content).second == 32"
                                  class="u-flex u-col-center u-flex-wrap">
                                <span class="nickname">{{ JSON.parse(msg.content).data.sendUserNick }}</span>在
                                <span class="target_nick">{{ JSON.parse(msg.content).data.roomTitle }}</span>送出了
                                <span class="gift_info">{{ JSON.parse(msg.content).data.giftName }}</span>
                            </view>
                            <view v-else
                                  class="u-flex u-col-center u-flex-wrap">
                                <span class="nickname">{{ JSON.parse(msg.content).data.nick }}</span>
                                <!-- 打赏 || 全麦打赏 -->
                                <span class="give_type_text">{{ JSON.parse(msg.content).first | filterGiveType(JSON.parse(msg.content).second) }}</span>
                                <!-- 被打赏 -->
                                <span class="target_nick"
                                      v-if="JSON.parse(msg.content).first != 12">{{ JSON.parse(msg.content).data.targetNick }}</span>
                                <!-- 普通送礼 -->
                                <image class="gift_img"
                                       v-if="JSON.parse(msg.content).data.gift"
                                       :src="JSON.parse(msg.content).data.gift.giftUrl"
                                       mode="" />
                                <span class="gift_info"
                                      v-if="JSON.parse(msg.content).data.gift">{{ JSON.parse(msg.content).data.gift.giftName }} x {{ JSON.parse(msg.content).data.giftNum }}</span>
                            </view>
                        </view>
                    </template>
                </view>
            </scroll-view>
        </view>
        <view class="bottom_box">
            <view>
                <input type="text"
                       placeholder="说点什么..."
                       placeholder-style="color:#FFFFFF"
                       v-model="chatVal"
                       @confirm="confirm">
                <button class="sendBtn"
                        @click="confirm">发送</button>
            </view>

            <view class="p2pMessage"
                  @click="openP2PMsg">
                <image src='../static/room1/message.png'></image>
                <text v-if="notLookCount">{{notLookCount}}</text>
            </view>
            <view class="voice"
                  @click="changeVoiceFlag">
                <image v-if="voiceFlag"
                       src='../static/room1/voice.png'></image>
                <image v-if="!voiceFlag"
                       src='../static/room1/voice_close.png'></image>
            </view>
            <view class="mic"
                  @click="changeMicFlag"
                  v-if="micQueue.find(i => i.uid == identity.uid)">
                <image v-if="micFlag"
                       src='../static/room1/openmic.png'></image>
                <image v-if="!micFlag"
                       src='../static/room1/closemic.png'></image>
            </view>
            <view class="shouchong"
                  @click="showGiftModel">
                <image src='../static/room1/shouchong.png'></image>
            </view>
            <view class="more"
                  @click="showManagePopup">
                <image src='../static/room1/more.png'></image>
            </view>
        </view>
        <uni-popup ref="popup_p2pMsgs"
                   type="bottom">
            <view class="p2pMsgCotainer">
                <view class="p2pList"
                      v-if="p2p_pop_type == 1">
                    <view class="P2pmsgTit">
                        <text>消息</text>
                    </view>
                    <scroll-view class="msg_scroll"
                                 scroll-y="true">

                        <view class="p2p-item"
                              v-for="(item,index) in p2pMsgArr"
                              :key="index"
                              @click="handleIntoMsgDetail(item)">
                            <view class="user">
                                <view class="userIcon">
                                    <image :src='item.avatar'></image>
                                </view>
                                <view class="tit">
                                    <view class="nick">{{item.nick}}</view>
                                    <view class="msg">{{item.lastMsg.text}}</view>
                                </view>
                            </view>
                            <view v-if="item.unread != 0"
                                  class="item-info-bottom_action">{{item.unread}}</view>
                            <!-- <view class="time">1分钟前</view> -->
                        </view>
                    </scroll-view>
                </view>

                <view class="detail"
                      v-if="p2p_pop_type == 2">
                    <view class="detail-tip">
                        <image class="back"
                               src="../static/room1/qert.png"
                               @click="handBackToP2PList"></image>
                        <text class="userNick">{{detailMsgSession.other.nick}}</text>
                    </view>

                    <scroll-view class="msg_scroll"
                                 scroll-y="true"
                                 :scroll-top="msgScrollTop">
                        <view :class="{ 'detail-item': true , 'detail-mine' : item.isMineFlag}"
                              v-for="(item,index) in detailMsgSession.msgs"
                              :key="index">
                            <!-- <view class="time">07-09 17:12</view> -->
                            <div class="detail-content">
                                <image class="user-icon"
                                       :src='item.isMineFlag ? item.mine.avatar: item.other.avatar '></image>
                                <view class="msg">
                                    {{item.text}}
                                </view>
                            </div>
                        </view>
                        <!-- <view :class="{ 'detail-item': true , 'detail-mine' : true}">
                            <view class="time">07-09 17:12</view>
                            <div class="detail-content">
                                <image class="user-icon"
                                       src='../static/room1/toushi.png'></image>
                                <view class="msg">
                                    我关注了你，让我们成为好友一起 聊天吧
                                </view>
                            </div>
                        </view> -->
                    </scroll-view>
                    <view class="sendBox">
                        <input type="text"
                               placeholder="请输入..."
                               placeholder-style="color:#E5DDFF"
                               v-model="p2pVal"
                               @confirm="sendP2PMsg">
                        <button class="sendBtn"
                                @click="sendP2PMsg">发送</button>
                    </view>
                </view>
            </view>
        </uni-popup>
        <view class="live-player-box">
            <live-player v-for="(item,index) in liveSrc"
                         :key="index"
                         :src="item.url"
                         mode="RTC"
                         autoplay
                         :id='item.uid'
                         @audiovolumenotify='playerVoice'
                         style="width: 0; height: 0;" />
            <view>{{item.url}}</view>
        </view>
        <!-- <live-pusher v-if="pushUrl != ''"
                     audio-quality="high"
                     style="height:0; width: 0"
                     :url="pushUrl"
                     mode="FHD"
                     :enable-camera="false"
                     id='livePusher'
                     ref="livePusher"
                     @statechange="statechange"
                     @netstatus="netstatus"
                     @error="error" /> -->

        <live-pusher id='livePusher'
                     ref="livePusher"
                     class="livePusher"
                     :url="pushUrl"
                     :enable-camera="false"
                     @statechange="statechange"
                     @netstatus="netstatus"
                     @error="pusherError"
                     @audiovolumenotify='pusherVoice'></live-pusher>

        <uni-popup ref="popup_edit"
                   type="bottom">
            <view class="editBox">
                <view class="picHeader">
                    <image class="bottomHeader"
                           src='../static/room1/bottomheader.png'></image>
                    <image class="userphoto"
                           :src="currentClickMicMsg.detailMsg.avatar">
                    </image>
                </view>

                <view class="command"
                      v-if="!currentClickMicMsg.isMine">
                    <text class="jubao"
                          @click="reportUser">举报</text>
                    <text class="manage"
                          v-if="currentInfo.role > 0"
                          @click="openManager">管理</text>
                </view>

                <view class="userNick">{{currentClickMicMsg.detailMsg.nick}}</view>
                <view class="brage">
                    <image :src="currentClickMicMsg.detailMsg.userLevelVo.weathLarge"></image>
                    <image :src="currentClickMicMsg.detailMsg.userLevelVo.charmLarge"></image>
                    <!-- 铭牌 -->
                    <image :src="currentClickMicMsg.detailMsg.userLevelVo.nameplateUrlAndText"></image>
                </view>
                <view class="msg">
                    <text>ID：{{currentClickMicMsg.detailMsg.erbanNo}}</text>
                    <text>粉丝：{{currentClickMicMsg.detailMsg.fansNum}}</text>
                </view>
                <view class="title">{{currentClickMicMsg.detailMsg.userDesc}}</view>
                <template>
                    <view v-if="!currentClickMicMsg.isMine"
                          class="_bottom">
                        <view class="follow"
                              @click="handFollowUser"
                              v-if="currentClickMicMsg.detailMsg.focusStatus == 0">关注</view>
                        <view class="has-follow"
                              @click="handFollowUser"
                              v-if="currentClickMicMsg.detailMsg.focusStatus == 1">已关注</view>
                        <view @click="handleIntoChat">聊天</view>
                        <view>主页</view>
                    </view>
                    <view class="family"
                          v-if="currentClickMicMsg.detailMsg.familyInfo">
                        <view class="familyIcon">
                            <image src='../static/room1/bb.png'></image>
                        </view>
                        <view class="_msg">
                            <view>{{currentClickMicMsg.detailMsg.familyInfo.familyName}}</view>
                            <view>
                                <text>ID: </text>
                                <text>{{currentClickMicMsg.detailMsg.familyInfo.familyId}}</text>
                            </view>
                            <view>
                                <image :src='currentClickMicMsg.detailMsg.familyInfo.icon'></image>
                                <text>8888</text>
                            </view>
                        </view>
                        <view class="usersIcon">
                            <image v-for="(item,index) in currentClickMicMsg.detailMsg.familyInfo.top3"
                                   :key="index"
                                   :src='item'>
                            </image>
                        </view>
                    </view>
                    <view v-if="currentClickMicMsg.isMine"
                          @click="handDisConnectMic"
                          class="disConnectMic">
                        <view>下麦旁听</view>
                    </view>
                </template>

            </view>
        </uni-popup>
        <view class="managerMethods">
            <uni-popup ref="manager"
                       type="bottom">
                <view class="box">
                    <view class="methods">
                        <view class="method"
                              @click="handSetMic"
                              v-if="currentClickMicMsg.msg.micState == 0">设闭麦位</view>
                        <view class="method"
                              @click="handSetMic"
                              v-if="currentClickMicMsg.msg.micState == 1">解除闭麦</view>
                        <view class="method"
                              @click="handSetLook"
                              v-if="currentClickMicMsg.msg.posState == 0">锁定麦位</view>
                        <view class="method"
                              @click="handSetLook"
                              v-if="currentClickMicMsg.msg.posState == 1">解锁麦位</view>
                        <view v-if="currentClickMicMsg.msg.uid"
                              class="method"
                              @click="handPollMic">抱Ta下麦</view>
                        <view v-if="!currentClickMicMsg.msg.uid"
                              @click="openMebmerList"
                              class="method">抱Ta上麦</view>
                        <view v-if="!currentClickMicMsg.msg.uid"
                              @click="handleIntoPosition"
                              class="method">移到此座位</view>
                        <view v-if="currentClickMicMsg.msg.uid &&  currentClickMicMsg.msg.uid == this.identity.uid"
                              @click="handleIntoPosition"
                              class="method">下麦旁听</view>
                        <view class="bg"></view>
                        <view class="method"
                              @click="closeManager">取消</view>
                    </view>
                </view>
            </uni-popup>
        </view>
        <uni-popup ref="popup_members"
                   type="right"
                   backgroundColor='#A020F0'>
            <view class="popup_members">

                <view class="goBack">
                    <image src="../static/room1/qert.png"
                           @click="closePopupMembers"></image>
                    <text class="title">在线听众</text>
                </view>

                <view class="user_item"
                      v-for="(item,index) in memberList.filter(ele =>  !(micQueue.find(i => i.uid == ele.account)) )"
                      :key="index">
                    <view class="user">
                        <view class="pic"
                              @click="handOfferQueen(item)">
                            <image :src="item.avatar"></image>
                        </view>
                        <view class="right">
                            <text class="nick">{{item.nick}}</text>
                            <view class="brage"
                                  v-if="item.custom">
                                <image :v-if="JSON.parse(item.custom)[item.account].wealthLarge"
                                       :src="JSON.parse(item.custom)[item.account].wealthLarge"></image>
                                <image :v-if="JSON.parse(item.custom)[item.account].charmLarge"
                                       :src="JSON.parse(item.custom)[item.account].charmLarge"></image>
                                <!-- 铭牌 -->
                                <image :v-if="JSON.parse(item.custom)[item.account].nameplateUrlAndText"
                                       :src="JSON.parse(item.custom)[item.account].nameplateUrlAndText"></image>
                            </view>
                        </view>
                    </view>
                </view>

            </view>
        </uni-popup>

        <!-- 礼物弹框 -->
        <uni-popup ref="giftPopup"
                   id="giftPopup"
                   type="bottom">
            <view class="gift_box">
                <view class="give_user_box u-flex u-col-center">
                    <view class="give_tip">送给：</view>
                    <!-- 房间用户送礼选择 -->
                    <view class="give_user_scroll">
                        <scroll-view scroll-x
                                     scroll-with-animation
                                     :show-scrollbar="false">
                            <view style="padding:10rpx 0"
                                  class="u-flex">
                                <!-- <view v-if="!userPositionList.find(ele => ele.uid == roomUid)" class="user_item"
                                      :class="{ 'active': roomParamsState.select }"
                                      @click="changeUserSelect(roomParamsState)">
                                </view> -->
                                <view class="user_item"
                                      v-for="(item,index) in userPositionList"
                                      :key="index"
                                      :class="{ 'active': item.select }"
                                      @click="changeUserSelect(item,index)">
                                    <image class="user_avatar"
                                           :src="item.avatar"
                                           mode="" />
                                    <view class="role_box">{{ item.role | roleFilter(index) }}</view>
                                </view>
                            </view>
                        </scroll-view>
                        <view class="mantle"></view>
                    </view>

                    <view class="give_select_btn"
                          @click="changeGiveUser"
                          :class="{'isall': giveAll }"> {{ giveAll ? '取消全麦' :'全麦' }}</view>
                </view>
                <view class="line_box"></view>
                <view class="gift_title_box u-flex">
                    <view class="u-flex"
                          v-for="(item,index) in titleList"
                          :key="index"
                          @click="changeTitleActiveIndex(index)">
                        <view class="title"
                              :class="{ 'active': titleActiveIndex == index }">{{ item }}</view>
                        <view v-if="index != titleList.length-1"
                              class="line"></view>
                    </view>
                </view>
                <view v-if="titleActiveIndex==3"
                      class="give_all u-flex u-row-between u-col-center">
                    <view class="give_all_num">总价：{{ allGoldPrice }}</view>
                    <view class="give_all_btn"
                          @click="sendAllGift">一键全送</view>
                </view>
                <scroll-view class="gift_scroll"
                             scroll-y="true">
                    <view class="u-flex u-flex-wrap">
                        <view class="gift_item u-flex-col u-col-center"
                              v-for="(item,index) in giftList[titleActiveIndex]"
                              :key="item.giftId"
                              :class="{ 'active': giftActiveIndex == index }"
                              @click="changeGiftActiveIndex(item,index)">
                            <view class="gift_count"
                                  v-if="titleActiveIndex == 3">x{{ item.count && item.count || 1}}</view>
                            <view class="gift_img_box u-flex u-col-center u-row-center">
                                <image class="gift_img"
                                       :src="item.giftUrl"
                                       mode="" />
                            </view>
                            <view class="title">{{ item.giftName }}</view>
                            <view class="price">{{ item.goldPrice }}金币</view>
                        </view>
                    </view>
                </scroll-view>
                <view class="foot_box u-flex u-row-between"
                      :class="{'u-row-right': isIOS}">
                    <view v-show="!isIOS"
                          class="gold_box  u-flex u-col-center">
                        <image class="gold_img"
                               src="/static/jb.png"
                               mode="" />
                        <view class="gold_num">{{ formatGoldNum(goldNum) }}</view>
                        <i class="iconfont icon-arrow-right"></i>
                        <view class="recharge_btn"
                              @click="gotoRecharge">充值</view>
                    </view>
                    <view class="give_box  u-flex u-col-center">
                        <view class="give_select_num u-flex  u-row-center"
                              @click="showSelectGive=!showSelectGive">
                            <view class="give_num">{{ currentGiveSelectData.num }}</view>
                            <i class="iconfont icon-arrow-right"></i>
                            <view v-show="showSelectGive"
                                  class="select_give_box">
                                <view class="select_give_item u-flex u-row-between u-col-center"
                                      v-for="(item,index) in giveSelectList"
                                      :key="index"
                                      @click="changeGiveSelect(item,index)">
                                    <view class="give_num">{{ item.num }}</view>
                                    <view class="give_name">{{ item.name }}</view>
                                </view>
                            </view>
                        </view>
                        <view class="give_btn"
                              @click="sendGift">赠送</view>
                    </view>
                </view>
            </view>
        </uni-popup>

        <uni-popup ref="popupManager"
                   type="bottom">
            <view class="manage_box u-flex u-row-between">
                <view class="item_box  u-flex-col  u-col-center"
                      v-for="(item,index) in manageList"
                      :key="index"
                      @click="changeItem(item,index)">
                    <image class="item_img"
                           :src="item.type? item.imgUrl : item.imgUrl1"
                           mode="" />
                    <p class="item_title">{{ !item.type ? item.title : item.title1 }}</p>
                </view>
            </view>
        </uni-popup>
        <uni-popup ref="insertPsd"
                   type="center">
            <view class="insertPsd">
                <view>设置房间密码</view>
                <view>
                    <input type="number"
                           v-model="insertPsd"
                           placeholder="请输入密码..."
                           maxlength="6"
                           @input="handlePsdChange">
                </view>
                <button @click="onConfirmPsd">确定</button>
            </view>
        </uni-popup>
        <uni-popup ref="editPsd"
                   type="bottom">
            <view class="editPsd">
                <view class="methods">
                    <view class="method"
                          @click="editPsd">修改密码</view>
                    <view class="method"
                          @click="closePsd">房间解锁</view>
                    <view class="method">取消</view>
                </view>

            </view>
        </uni-popup>
        <uni-popup ref="enterPsd"
                   type="center">
            <view class="insertPsd">
                <view>输入房间密码</view>
                <view>
                    <input type="number"
                           v-model="enterPsd"
                           placeholder="请输入密码..."
                           maxlength="6">
                </view>
                <button @click="handleEnterPsd">确定</button>
            </view>
        </uni-popup>
    </view>
</template>


<script>
import NIM from '../libs/NIM_Web_NIM_miniapp_v8.9.0'
import ChatRoom from '../libs/NIM_Web_Chatroom_miniapp_v8.9.0.js'
import {
    mapState
} from 'vuex';
import {
    renderMessageType
} from './utils/messageType.js'
var nimInstance, chatRoomInstance, agoraClient;

// const appKey = '9bbedb58f17bba7bbf3256f43c8cab91' //云信appKey
const RoomStatus = {
    0: '锁定',
    1: '正常',
    2: '闭麦'
}

const AgoraMiniappSDK = require('../libs/Agora_Miniapp_SDK_for_WeChat.js');
//const agoraKey = '8a48959943954598b44c37c450a6a9db';
import {
    des_encrypt,
} from '@/common/encryption.js';

let timerFlag = true;

export default {
    computed: mapState(['hasLogin', 'user', 'identity', 'tickets']),
    data() {
        return {
            roomParamsState: {},
            micQueue: [],
            chatMsgArr: [`温馨提示：官方人员不会要求您提供个人信息
                        相关内容，顽皮平台倡导健康绿色聊天，若聊

                        天内容或则用户行为设计任何违反国家法律法规，

                        平台用户管理规则、暴力、涉黄、低俗、欺诈等任

                        何违规信息，平台官方将采取封号处理，若发现

                        违规行为，请积极联系官方处理。`, `可点击房间公告查看本房间玩法`],
            renderMessageType: renderMessageType,
            scrollTop: 0,
            msgScrollTop: 0,
            scrollTopTimer: null,
            chatVal: '',
            memberList: [],
            mineChatMsg: {},
            roomInfo: {}, // 房间信息
            titleList: ['福袋', '活动', '礼物', '背包', '特权'],
            titleActiveIndex: 2,  // 当前礼包
            giftList: [[], [], [], [], [],],       // 所有类型礼物List
            allLuckyGiftList: [],		// 未分类是的礼物列表
            currentClickMicMsg: {
                owner: false, //权限用户 （房主）
                isMine: false, //是否是自己
                msg: {}, //点中坑位上的信息
                detailMsg: null
            },
            newRoomFlag: false,
            liveSrc: [],
            p2pVal: '',
            p2pMsgArr: [],
            detailMsgSession: {},
            notLookCount: 0,
            p2p_pop_type: 1, //1表示列表 ， 2表示聊天详情
            voiceFlag: true,
            micFlag: true, //自己是否打开麦克风
            giftValueVos: [],
            pushUrl: '',
            currentInfo: {},
            isFavor: true,
            roomUid: null,
            ownerErbanNo: null,
            timer: null,
            // timerFlag: true,
            giftActiveIndex: -1,    // 当前选中礼物
            currentSelctGive: null, // 当前选中礼物对象

            goldNum: 0,  // 用户金币余额
            giveSelectList: [  //  送礼数量列表
                { num: 1, name: '一心一意' }, { num: 10, name: '十全十美' }, { num: 66, name: '一切顺利' }, { num: 99, name: '长长久久' },
                { num: 188, name: '要抱抱' }, { num: 520, name: '我爱你' }, { num: 1314, name: '一生一世' },
            ],
            currentGiveSelectData: {},  // 当前选中礼物数量套餐

            showSelectGive: false,  // 是否显示礼物数量套餐选择
            giveAll: false,  // 是否全麦
            giveAnimationList: [],  // 当前礼物动画对象
            giveAnimationList2: [], // 当前礼物动画对象
            windowWidth: 375,   // 设备宽度
            endXYList: [],  // 送礼麦位位置
            defaultUserPositionList: [],  //  麦位默认坐标列表
            userPositionList: [],      // 当前房间用户所在麦位信息
            giftAnimationTimer: '',
            allGoldPrice: 0,     // 用户背包礼物总价值
            giftBoxTop: 300,	// 控制礼物动画掉下的最大高度
            giftContentFirst: 3,     //  区分是否全麦送礼
            selectGiveUserNum: 0,
            selectUserArr: [], //	当前送礼选中的用户uid
            isIOS: this.$isIOS,
            activityList: [],   //  活动banner
            filterFirstList: [46, 88, 26, 16, 2, 92, 50, 62, 93, 95],     // 公屏消息过滤
            manageList: [
                { imgUrl1: require('../static/room1/roomLock.png'), title1: '房间已锁', type: false, imgUrl: require('../static/room1/roomLock1.png'), title: '房间上锁', },
                { imgUrl: require('../static/room1/closeGift.png'), title: '开启礼物值', type: false, imgUrl1: require('../static/room1/closeGift1.png'), title1: '关闭礼物值', },
                { imgUrl: require('../static/room1/closePublicScreen1.png'), title: '关闭公屏', type: false, imgUrl1: require('../static/room1/closePublicScreen.png'), title1: '开启公屏', },
                { imgUrl: require('../static/room1/cleanPublicScreen.png'), title: '清除公屏', type: false, imgUrl1: require('../static/room1/cleanPublicScreen.png'), title1: '清除公屏', },
            ],
            insertPsd: '',
            enterPsd: '',
            psdResolve: null,
        }
    },

    watch: {
        roomInfo: {
            handler(newVal, oldVal) {
                this.manageList[0].type = Boolean(newVal.roomPwd)       // 房间上锁状态
                this.manageList[1].type = newVal.showGiftValue    // 是否展示礼物值
                this.manageList[2].type = newVal.isCloseScreen    // 是否开启公屏
                if (newVal.cleanScreenTime > oldVal.cleanScreenTime && oldVal != 0) { //清除公屏
                    console.log('清除公屏')
                    this.chatMsgArr = [`温馨提示：官方人员不会要求您提供个人信息
                        相关内容，顽皮平台倡导健康绿色聊天，若聊

                        天内容或则用户行为设计任何违反国家法律法规，

                        平台用户管理规则、暴力、涉黄、低俗、欺诈等任

                        何违规信息，平台官方将采取封号处理，若发现

                        违规行为，请积极联系官方处理。`, `可点击房间公告查看本房间玩法`]
                }
                console.log('>><<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<', newVal.valid, newVal.showGiftValue, newVal.isCloseScreen);
            },
            deep: true
        },
        userPositionList: {
            handler(newVal, oldVal) {
                let selectUserNum = 0
                if (newVal.length != oldVal.length) {
                    newVal.forEach(ele => {
                        if (ele.uid) {
                            ele.select = false
                        }
                    });
                    this.giveAll = false
                }
                newVal.forEach(ele => {
                    if (ele.uid) {
                        if (ele.select) {
                            selectUserNum++
                        }
                        // 0:房主  1：超管   2：管理员
                        this.$api.roomUserGet({
                            uid: this.identity.uid,
                            roomUid: this.roomUid,
                            targetUid: ele.uid,
                        }).then(res => {
                            ele.role = res.data.role;
                        })
                    }
                });
                if (selectUserNum == newVal.length) {
                    this.giveAll = true
                } else {
                    this.giveAll = false
                }
            },
            deep: true
        },

        micQueue: {
            handler(newVal, oldVal) {
                newVal.forEach(ele => {
                    if (ele.uid) {
                        // 0:房主  1：超管   2：管理员
                        this.$api.roomUserGet({
                            uid: this.identity.uid,
                            roomUid: this.roomUid,
                            targetUid: ele.uid,
                        }).then(res => {
                            ele.role = res.data.role;
                        })
                    } else {
                        ele.role = ''
                    }
                });
            },
            deep: true
        },

        titleActiveIndex(newV) {
            // this.currentGiftList = this.giftList[newV]
            switch (newV) {
                case 0:
                    break;
                case 1:
                    break;
                case 2:
                    // this.getGiftList()
                    break;
                case 3:
                    this.getUserBackpack()
                    break;
                case 4:
                    this.getRoomVipCardList()
                    break;
            }
        },
    },
    filters: {
        filterGiveType(first, second) {
            let text = ''
            switch (first) {
                case 3:
                    text = '打赏'
                    return text;
                case 12:
                    // 全麦送礼
                    text = '全麦打赏'
                    return text;
            }
        },
        roleFilter(type, index) {
            switch (type) {
                case 1:
                    return '超管';
                case 2:
                    return '管理';
                case 3:
                    return '房主';
                default:
                    return index
            }
        },
    },
    // 小程序自定义分享
    onShareAppMessage(res) {
        var _this = this;
        return {
            title: `邀请您进入${_this.userPositionList[0].title}，快来一起聊天吧~`,
            path: `house/liveHouse/liveHouse?owner=${_this.roomParamsState.owner}&roomId=${_this.roomUid}&erbanNo=${_this.roomParamsState.erbanNo}`,
            // imageUrl: _this.orderDetail.skuPic,
        }

    },
    onShow() {
        // 获取用户钱包信息
        this.getWallet()
    },
    onLoad(params) {
        this.$interactive.showLoading('加载中...')
        this.roomParamsState = params;
        this.handleCurrRoomUserGet();
        setTimeout(() => {
            // 注意：需要在onReady中 或 onLoad 延时
            this.context = uni.createLivePusherContext("livePusher", this);
        }, 1000);
        setTimeout(() => {
            this.$interactive.hideLoading()
        }, 5000);

        let _this = this
        uni.getSystemInfo({
            success: function (e) {
                _this.windowWidth = e.windowWidth
            }
        })
        this.getGiftList()
        this.invalidGifts();
        this.giftValGet();

        this.currentGiveSelectData = this.giveSelectList[0]

        this.initNIM();
        this.micQueue = ['-1', '0', '1', '2', '3', '4', '5', '6', '7'].map(item => ({
            "position": item,
            "posState": 0,
            "micState": 0,
            "uid": null,
            avatar: "",
            gender: null,
            nick: "",
        }))
        this.getActivity()
    },
    mounted() {
        setTimeout(() => {
            this.initUserPosition()
        }, 500);
    },
    onUnload() {
        agoraClient && agoraClient.leave();
        nimInstance && nimInstance.destroy();
        chatRoomInstance && chatRoomInstance.disconnect();
        chatRoomInstance && chatRoomInstance.disconnect();
        chatRoomInstance.destroy({
            done: function (err) {
                console.log('实例已被完全清除')
            }
        })
        console.log('11111', chatRoomInstance.disconnect)
        console.log('22222', chatRoomInstance.destroy)
    },
    methods: {
        //获取当前用户信息
        handleCurrRoomUserGet() {
            const { uid } = this.identity;
            const { owner, roomId } = this.roomParamsState;
            this.roomUid = owner == 'true' ? uid : roomId,
                this.$api.roomUserGet({
                    uid,
                    roomUid: this.roomUid,
                    targetUid: uid,
                }).then((res) => {
                    // res.data.role = 1;
                    console.log(res);
                    console.log('当前用户信息', res.data)
                    this.currentInfo = res.data;
                })

            this.$api.roomUserGet({
                uid,
                roomUid: this.roomUid,
                targetUid: this.roomUid,
            }).then((res) => {
                // res.data.role = 1;
                this.ownerErbanNo = res.data.erbanNo;
                console.log(this.ownerErbanNo)
            })
        },

        handleConnect() {
            //收藏
            console.log('handleConnect')
            this.$api.favoriteAdd({
                roomUid: this.roomUid,
                uid: this.identity
                    .uid
            }).then((res) => {
                this.isFavor = true;
            })
        },

        handleIntoChat() {
            console.log('私信')
            const { avatar, uid, nick } = this.currentClickMicMsg.detailMsg;
            const params = {
                avatar,
                id: `p2p-${uid}`,
                nick,
                to: uid
            }
            this.close()
            this.handleIntoMsgDetail(params, true)
        },

        playerVoice(e) {
            // console.log('远端用户声音发生变化+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++', e.target)
            const { id, volume } = e.target;
            if (this.micQueue.find(item => item.uid == id)) {
                this.$set(this.micQueue, this.micQueue.findIndex(item => item.uid == id), {
                    ... this.micQueue.find(item => item.uid == id),
                    // lastMsg: session.lastMsg,
                    volume
                })
                // console.log(this.micQueue)
            }


        },

        pusherVoice(e) {
            // console.log('自己声音发生变化+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++', e.target)
            const { volume } = e.target;
            const id = this.identity.uid;
            if (this.micQueue.find(item => item.uid == id)) { //自己在麦位上
                this.$set(this.micQueue, this.micQueue.findIndex(item => item.uid == id), {
                    ... this.micQueue.find(item => item.uid == id),
                    volume
                })
                // console.log(this.micQueue)
            }
        },

        handlePsdChange(e) {
            let i = e.target.value
            let num = i.charAt(i.length - 1)
            var reg = new RegExp("^[0-9]*$")
            if (!reg.test(num)) {
                setTimeout(() => { this.insertPsd = i.slice(0, -1) }, 0)
            }
        },


        disHandleConnect() {
            this.$api.favoriteRemove({
                roomUid: this.roomUid,
                uid: this.identity
                    .uid
            }).then((res) => {
                this.isFavor = false;
            })
        },

        renderOuth(role) {
            console.log(role)
            switch (role) {
                case 1:
                    return '管';
                case 2:
                    return '管';
                case 3:
                    return '房';
                default:
                    return ''
            }
        },

        //返回上一页
        handleGoBack() {
            uni.navigateBack()
        },
        // 格式化用户余额金币
        formatGoldNum(num) {
            if (num >= 10000) {
                let formatNum = Math.round(num / 1000) / 10
                if (formatNum > 9999) {
                    num = 9999 + '万+'
                } else {
                    num = formatNum + '万+'
                }
            }
            return num;
        },
        // 获取bannerH5活动
        getActivity() {
            this.$apiQjc.getActivity({ type: 2 }).then(res => {
                console.log(res);
                if (res.code == 200) {
                    this.activityList = res.data
                }
            })
        },
        // 跳转webview
        goActiveWebView(item) {
            switch (item.skipType) {
                case 2:
                    // 房间
                    uni.reLaunch({
                        url: '/pages/liveHouse/liveHouse'
                    });
                    break;
                case 3:
                    // H5
                    uni.navigateTo({
                        url: `/pages/activeWebView/activeWebView?vurl=${item.skipUrl}`
                    });
                    break;
            }
        },
        close() {
            this.$refs.popup_edit.close()
        },
        open() {
            // 通过组件定义的ref调用uni-popup方法 ,如果传入参数 ，type 属性将失效 ，仅支持 ['top','left','bottom','right','center']
            this.$refs.popup_edit.open()
        },
        // 举报用户H5
        reportUser() {
            console.log('--------------------------this.currentClickMicMsg', this.currentClickMicMsg);
            let reportUserUrl = `${this.$urlConfig.h5_config}wanpi/app/reportCenter/?reportUid=${this.currentClickMicMsg.detailMsg.uid}&uid=${this.identity.uid}&reportType=5`
            uni.navigateTo({
                url: `/pages/activeWebView/activeWebView?vurl=${escape(reportUserUrl)}`
            });
        },
        openManager() {
            // 通过组件定义的ref调用uni-popup方法 ,如果传入参数 ，type 属性将失效 ，仅支持 ['top','left','bottom','right','center']
            this.$refs.manager.open()
        },
        closeManager() {
            this.$refs.manager.close()
        },
        openPopupMembers() {
            this.$refs.popup_members.open()
        },
        closePopupMembers() {
            this.$refs.popup_members.close()
        },
        openP2PMsg() {
            this.p2p_pop_type = 1;
            this.notLookCount = 0
            this.$refs.popup_p2pMsgs.open();

        },
        colseP2PMsg() {
            console.log('close')
            this.$refs.popup_p2pMsgs.close()
        },

        //初始化云信账号
        initNIM() {
            const {
                uid,
                netEaseToken
            } = this.identity;
            return new Promise((resolve, reject) => {
                var _nim = NIM.getInstance({
                    debug: false, // 是否开启日志，将其打印到console。集成开发阶段建议打开。
                    appKey: this.$urlConfig.appKey,
                    account: uid,
                    token: netEaseToken,
                    db: true, //若不要开启数据库请设置false。SDK默认为true。
                    onconnect: this.onConnect,
                    onwillreconnect: this.onWillReconnect,
                    ondisconnect: this.onDisconnect,
                    onerror: this.onError,
                    // onmsg: (msg) => {
                    //     console.log(msg)
                    //     if (msg.scene == "p2p" && msg.type == 'text') {
                    //         // this.acc

                    //         this.notLookCount += 1;
                    //     }
                    // },
                    onsessions: async (sessions) => {
                        console.log('sessions', sessions)
                        let p2pTextMsgs = nimInstance.mergeSessions(this.p2pMsgArr, sessions)
                        p2pTextMsgs = p2pTextMsgs.filter(ele => ele.scene == 'p2p' && ele.lastMsg.type == 'text');
                        for (let i in p2pTextMsgs) {
                            await this.$api.userDetail({
                                uid: this.identity.uid,
                                ticket: this.tickets[0].ticket,
                                targetUid: sessions[i].to,

                            }).then((res) => {
                                p2pTextMsgs[i].avatar = res.data.avatar;
                                p2pTextMsgs[i].nick = res.data.nick;
                            })
                        }
                        this.p2pMsgArr = p2pTextMsgs;
                    },
                    onupdatesession: async (sessions) => {
                        console.log('onupdatesession', sessions)
                        if (this.p2pMsgArr.find(i => i.to == sessions.to)) {
                            this.$set(this.p2pMsgArr, this.p2pMsgArr.findIndex(i => i.to == sessions.to), {
                                ...this.p2pMsgArr.find(i => i.to == sessions.to),
                                ...sessions,
                            })
                            if (sessions.lastMsg.from != this.identity.uid) {
                                if (this.detailMsgSession && this.detailMsgSession.msgs) {
                                    this.detailMsgSession.msgs.push({
                                        ...sessions.lastMsg,
                                        mine: this.user,
                                        other: this.detailMsgSession.other,
                                        isMineFlag: false,
                                    })
                                    //滚动到底部
                                }
                                this.msgScrollTop += 80
                            }

                        }

                        let p2pTextMsgs = nimInstance.mergeSessions(this.p2pMsgArr, sessions)
                        p2pTextMsgs = p2pTextMsgs.filter(ele => ele.scene == 'p2p' && ele.lastMsg.type == 'text');
                        for (let i in p2pTextMsgs) {
                            await this.$api.userDetail({
                                uid: this.identity.uid,
                                ticket: this.tickets[0].ticket,
                                targetUid: p2pTextMsgs[i].to,

                            }).then((res) => {
                                p2pTextMsgs[i].avatar = res.data.avatar;
                                p2pTextMsgs[i].nick = res.data.nick;
                            })
                        }
                        this.p2pMsgArr = p2pTextMsgs;
                    },
                });
                nimInstance = _nim;
            })
        },
        onConnect() {
            console.log('---------连接成功---------');
            if (this.roomParamsState.owner == 'true') {
                //创建房间
                this.createChatRoom()
            } else {
                //加入房间
                this.joinToRoom(this.roomUid)
            }

        },
        onError(error) {
            console.log(error);
        },
        onDisconnect(error) {
            console.log('丢失连接');
            console.log(error);
            if (error) {
                switch (error.code) {
                    // 账号或者密码错误, 请跳转到登录页面并提示错误
                    case 302:
                        break;
                    // 重复登录, 已经在其它端登录了, 请跳转到登录页面并提示错误
                    case 417:
                        break;
                    // 被踢, 请提示错误后跳转到登录页面
                    case 'kicked':
                        break;
                    default:
                        break;
                }
            }
        },
        onwillreconnect(error) {
            // 此时说明 SDK 已经断开连接, 请开发者在界面上提示用户连接已断开, 而且正在重新建立连接
            console.log('即将重连');
            console.log(obj.retryCount);
            console.log(obj.duration);
        },

        //获取房间信息
        createChatRoom() {
            console.log('房主端获取房间信息')
            this.$api.getRoom({
                uid: this.identity.uid,
                roomUid: this.roomUid,
            }).then((res) => {
                if (res.data.roomId) { //房间异常中断 ，已经有房间
                    this.initChatRoom(res.data.roomId);
                    this.roomInfo = res.data

                } else { //没有房间 ，新开房间
                    const openParams = {
                        uid: this.identity.uid,
                        title: this.user.nick + this.identity.uid
                    };
                    this.$api.roomOpen(openParams).then(res => {
                        this.newRoomFlag = true;
                        this.initChatRoom(res.data.roomId);
                        this.roomInfo = res.data
                    })
                }

            })


        },

        //用户端加入房间
        joinToRoom(roomId) {
            console.log('用户端加入房间')
            this.$api.getRoom({
                uid: this.identity.uid,
                roomUid: roomId,
            }).then(async (res) => {
                this.roomInfo = res.data;
                if (this.roomInfo.roomPwd && this.currentInfo.role != 3) {
                    console.log('房间已经上锁', des_encrypt('123456'))
                    //我写到了这里
                    await new Promise((psdResolve) => {
                        this.psdResolve = psdResolve;
                        this.$refs.enterPsd.open()
                    })
                    this.initChatRoom(res.data.roomId)
                } else {
                    this.initChatRoom(res.data.roomId)
                }


            })
        },

        //获取聊天室地址
        initChatRoom(chatroomId) {
            nimInstance.getChatroomAddress({
                chatroomId,
                done: (error, obj) => {
                    console.log('获取聊天室地址' + (!error ? '成功' : '失败'), error, obj);
                    if (!error) {
                        this.getChatRoomInstance(obj)
                    }
                }
            });
        },

        //生成聊天室实例
        async getChatRoomInstance(obj) {
            const {
                uid,
                netEaseToken
            } = this.identity;
            console.log('+++++++++++++++++生成聊天室实例+++++++++++++++')
            const { userLevelVo } = this.user;
            const {
                chatroomId,
                address
            } = obj;
            var _chatroom = ChatRoom.getInstance({
                appKey: this.$urlConfig.appKey,
                account: uid,
                token: netEaseToken,
                chatroomId,
                chatroomAddresses: address,
                chatroomCustom: JSON.stringify({
                    [uid]: {
                        // charmLarge: "https://img.q17z.com/meili00_5.png",
                        // charmLevelSeq: 1,
                        // charmUrl: "https://img.q17z.com/x_meili00_4.png",
                        // clicked: false,
                        // defAvatar: "http://nim.nos.netease.com/NDI3OTA4NQ==/bmltd18wXzE1MDU0NDA3NzIxOTlfYzM2ZmU1NWEtODFmMC00NjU3LTgyMzEtYTZiMDY2ZTllYTFi",
                        // defUser: 5,
                        // entry_effect: "https://img.q17z.com/jinchang06_001.svga",
                        // fromType: 0,
                        // gender: 2,
                        // hasPrettyErbanNo: false,
                        // isRichGroup: false,
                        // is_mute_mic: false,
                        // newUser: false,
                        // official: false,
                        // source: 10,
                        // sourceUser: {
                        //     nick: "goujbbushi",
                        //     uid: uid
                        // },
                        // // nameplateUrlAndText:"https://img.q17z.com/铭牌.png+圣归来",
                        // wealthBackground: "",
                        // wealthLarge: "https://img.q17z.com/caifu00_4.png",
                        // wealthLevelSeq: 1,
                        // wealthUrl: "https://img.q17z.com/x_caifu00_4.png",
                        // wealthVggCar: "",
                        ...userLevelVo,
                        is_mute_mic: false,
                        sourceUser: {
                            nick: this.user.nick,
                            uid: uid
                        },
                        wealthLarge: userLevelVo.weathLarge,
                        wealthLevelSeq: 1,
                        wealthUrl: userLevelVo.wealthUrl,
                        roomMemberType: this.currentInfo.role == 3 ? 1 :
                            (this.currentInfo.role == 1 || this.currentInfo.role == 2) ? 2 : 0
                    }
                }),

                onconnect: (obj) => {
                    console.log('连接聊天室成功');
                    chatRoomInstance = _chatroom;
                    this.mineChatMsg = obj.member;
                    this.getChatroomMembers(true)
                    //获取30条聊天记录
                    chatRoomInstance.getHistoryMsgs({
                        limit: 30,
                        msgTypes: ['text'],
                        done: (error, obj) => {
                            console.log('historyMsgs', obj.msgs)
                            for (let i in obj.msgs) {
                                const msg = obj.msgs[i];
                                this.chatMsgArr = [
                                    ...this.chatMsgArr,
                                    msg
                                ]
                                this.scrollTop += 500;
                            }
                        }
                    })

                    if (this.newRoomFlag) {//新开的房间 更新聊天室拓展字段
                        console.log('新开的房间 ， 更新聊天室拓展字段')
                        let newMicQueue = {};
                        for (let i = 0; i < this.micQueue.length; i++) {
                            const _cur = this.micQueue[i];

                            newMicQueue[_cur.position] = JSON.stringify({
                                position: Number(_cur.position),
                                posState: Number(_cur.posState),
                                micState: Number(_cur.micState)
                            })

                        }

                        chatRoomInstance.updateChatroom({
                            chatroom: {
                                custom: JSON.stringify({
                                    micQueue: JSON.stringify(newMicQueue),
                                    roomInfo: JSON.stringify(this.roomInfo)
                                })
                            },
                            needNotify: true,
                            needSave: true,
                        })
                    } else {
                        const {
                            chatroom,
                        } = obj;
                        let {
                            micQueue,
                            roomInfo
                        } = JSON.parse(chatroom.custom);
                        console.log('micQueue', JSON.parse(micQueue))
                        console.log('roomInfo', JSON.parse(roomInfo))
                        micQueue = JSON.parse(micQueue);
                        this.micQueue = ['-1', '0', '1', '2', '3', '4', '5', '6', '7'].map(item => { //只更新坑位状态信息
                            return {
                                ...JSON.parse(micQueue[item]),
                                left: this.defaultUserPositionList[item.position + 1] && this.defaultUserPositionList[item.position + 1].left,
                                top: this.defaultUserPositionList[item.position + 1] && this.defaultUserPositionList[item.position + 1].top,
                                uid: '',
                                avatar: "",
                                gender: null,
                                nick: ""
                            }
                        })
                        this.roomInfo = JSON.parse(roomInfo);
                        this.getQueueList();
                    }
                    this.giftValGet()
                    this.handleFetchUserIn();
                    this.initAgora(chatroomId, uid)
                    // this.$interactive.hideLoading()
                },
                onerror: (error, obj) => {
                    console.log('发生错误', error, obj);
                    this.$interactive.hideLoading()
                },
                onwillreconnect: (obj) => {
                    console.log('即将重连', obj);
                },
                ondisconnect: (error) => {
                    if (error) {
                        switch (error.code) {
                            // 账号或者密码错误, 请跳转到登录页面并提示错误
                            case 302:
                                break;
                            // 被踢, 请提示错误后跳转到登录页面
                            case 'kicked':
                                break;
                            default:
                                break;
                        }
                    }
                },
                // 消息
                onmsgs: async (msgs) => {
                    console.log('onmsgs----------', msgs)
                    if (msgs[0]) {
                        for (let i in msgs) {
                            const msg = msgs[i];
                            if (msg.content && this.filterFirstList.findIndex(index => index == JSON.parse(msg.content).first) > 0) {
                                console.log('信息过滤----------', JSON.parse(msg.content).first, this.filterFirstList.findIndex(index => index == JSON.parse(msg.content).first))
                                continue
                            }
                            // console.log('收到聊天室消息', JSON.parse(msg.fromCustom), msg);
                            if (msg.type == "notification") { //带有拓展字段的通知消息（队列 & 聊天室拓展字段更新 ）
                                await this.handleNotificationMsg(msg)
                            }
                            if (msg.type == "custom") {

                                //  this.handGiveGiftMsg(msg)
                                /** 送礼特效
                                 * uid    送礼人id
                                 * targetUids   收礼人ids
                                 * gift.giftUrl     礼物图片
                                 * giftNum      礼物数量
                                 */
                                let msgContent = JSON.parse(msg.content)
                                console.log('----------------送礼消息item', msgContent)
                                switch (msgContent.first) {
                                    case 12:
                                        switch (msgContent.second) {
                                            case 121:
                                                // 普通全麦送礼
                                                console.log('---------------普通全麦送礼')
                                                break;
                                            case 122:
                                                // 福袋全麦礼物
                                                console.log('---------------福袋全麦礼物')
                                                break;
                                        }
                                        break;
                                    case 3:
                                        switch (msgContent.second) {
                                            case 31:
                                                // 普通送礼、活动、背包
                                                console.log('---------------单人普通送礼、活动、背包')
                                                break;
                                            case 33:
                                                // 福袋送礼
                                                console.log('---------------单人福袋送礼')
                                                break;
                                            case 38:
                                                // 特权
                                                console.log('---------------单人特权送礼')
                                                break;
                                        }
                                        break;
                                    case 42:
                                        switch (msgContent.second) {
                                            case 421:
                                                // 更新礼物值

                                                break;
                                        }
                                }

                                // 多人福袋
                                if (msgContent.data.luckyGiftList && msgContent.data.luckyGiftList.length > 0) {
                                    msgContent.data.luckyGiftList.forEach((luckyGiftEle, index) => {
                                        // 福袋爆出的礼物
                                        let luckyBagGift = this.allLuckyGiftList.find(ele => ele.giftId == luckyGiftEle.giftId)
                                        luckyGiftEle.giftUrl = luckyBagGift && luckyBagGift.giftUrl
                                        luckyGiftEle.goldPrice = luckyBagGift.goldPrice
                                        console.log('----!!!!!!!!!!!!!!!!!!!!!!!!', luckyGiftEle.goldPrice, luckyBagGift.goldPrice, luckyBagGift)
                                        this.addAnimation(luckyGiftEle.targetUids, luckyGiftEle.giftUrl)
                                    });
                                } else {
                                    // 单人福袋
                                    let giftData = msgContent.data
                                    giftData.giftUrl = giftData.gift && giftData.gift.giftUrl
                                    this.addAnimation(giftData.targetUids || [giftData.targetUid], giftData.giftUrl)
                                }
                                msg.content = JSON.stringify(msgContent)
                                this.handCustonMsg(msg)
                            }
                            setTimeout(() => {
                                this.chatMsgArr = [
                                    ...this.chatMsgArr,
                                    msg
                                ]
                                this.scrollTop += 50;
                            }, 500);

                        }
                        // msgs.map(async (msg) => {
                        //     // 未知信息过滤

                        // })
                        this.giftValGet()
                    }
                }
            });
        },
        //聊天室自定义消息接收处理
        handCustonMsg(msg) {
            console.log('接受到云信自定义消息')
            let { content } = msg;
            content = JSON.parse(content);
            const { data, first, second } = content;
            const { micPosition, uid } = data;

            if (first == 8 && second == 81 && uid == this.identity.uid) { //抱用户上麦
                const mine = this.memberList.find(each => each.account == uid);
                const { avatar, nick, account } = mine;
                const { gender } = JSON.parse(mine.custom)[account];
                chatRoomInstance.queueOffer({
                    elementKey: micPosition,
                    elementValue: JSON.stringify({
                        avatar,
                        gender,
                        nick,
                        uid,
                    }),
                    transient: true,
                })
            } else if (first == 20 && second == 204) {
                console.log('系统消息', content)
            }
        },
        // 处理送礼消息
        async handGiveGiftMsg(msg) {
            /** 送礼特效
             * uid    送礼人id
             * targetUids   收礼人ids
             * gift.giftUrl     礼物图片
             * giftNum      礼物数量
             */
            let msgContent = JSON.parse(msg.content)
            console.log('----------------送礼消息item', msgContent)
            switch (msgContent.first) {
                case 12:
                    switch (msgContent.second) {
                        case 121:
                            // 普通全麦送礼
                            console.log('---------------普通全麦送礼')
                            break;
                        case 122:
                            // 福袋全麦礼物
                            console.log('---------------福袋全麦礼物')
                            break;
                    }
                    break;
                case 3:
                    switch (msgContent.second) {
                        case 31:
                            // 普通送礼、活动、背包
                            console.log('---------------单人普通送礼、活动、背包')
                            break;
                        case 33:
                            // 福袋送礼
                            console.log('---------------单人福袋送礼')
                            break;
                        case 38:
                            // 特权
                            console.log('---------------单人特权送礼')
                            break;
                    }
                    break;
                case 42:
                    switch (msgContent.second) {
                        case 421:
                            // 更新礼物值

                            break;
                    }
            }
            this.giftValGet()
            // 多人福袋
            if (msgContent.data.luckyGiftList && msgContent.data.luckyGiftList.length > 0) {
                msgContent.data.luckyGiftList.forEach((luckyGiftEle, index) => {
                    // 福袋爆出的礼物
                    let luckyBagGift = this.allLuckyGiftList.find(ele => ele.giftId == luckyGiftEle.giftId)
                    console.log('----!!!!!!!!!!!!!!!!!!!!!!!!', luckyBagGift)
                    luckyGiftEle.giftUrl = luckyBagGift && luckyBagGift.giftUrl
                    luckyGiftEle.goldPrice = luckyBagGift.goldPrice
                    msg.content = JSON.stringify(msgContent)
                    this.addAnimation(luckyGiftEle.targetUids, luckyGiftEle.giftUrl)
                });
            } else {
                // 单人福袋
                let giftData = msgContent.data
                giftData.giftUrl = giftData.gift && giftData.gift.giftUrl
                msg.content = JSON.stringify(msgContent)
                this.addAnimation(giftData.targetUids || [giftData.targetUid], giftData.giftUrl)
            }
        },
        // 系统通知处理
        async handleNotificationMsg(msg) {
            this.giftValGet()
            if (msg.attach.custom) { // 更新坑位状态
                let attach = msg.attach;
                let { type, custom } = attach;
                let _custom = JSON.parse(custom);
                if (type == 'updateChatroom') {
                    if (_custom.type == 2) { //更新坑位信息
                        const { micInfo } = _custom;
                        let _micInfo = JSON.parse(micInfo);
                        if (_custom.micInfo) { //更新麦位锁定静音信息
                            //判断当前用户是否在麦位上
                            const curUser = this.micQueue.find(item => item.uid == this.identity.uid)
                            if (curUser && curUser.position == _micInfo.position) { //自己所在坑位上的信息更新
                                if (curUser.micState != _micInfo.micState) { //自己所在坑位静音状态更新
                                    if (_micInfo.micState == 1) {
                                        agoraClient.muteLocal('audio', () => {
                                            console.log('停止发送本地用户的音视频流成功');
                                            // this.stop()
                                        })
                                    } else {
                                        if (this.micFlag) { //判断本地是否开启了禁音
                                            agoraClient.unmuteLocal('audio', () => {
                                                console.log('恢复发送本地用户的音视频流成功');
                                                this.start()
                                            })
                                        } else {
                                            agoraClient.muteLocal('audio', () => {
                                                console.log('停止发送本地用户的音视频流成功');
                                                // this.stop()
                                            })
                                        }

                                    }
                                }
                            }
                            this.micQueue = this.micQueue.map(ele => {
                                delete _micInfo.uid;
                                if (ele.position == _micInfo.position) {
                                    return {
                                        ...ele,
                                        ..._micInfo,
                                        left: this.defaultUserPositionList[ele.position + 1] && this.defaultUserPositionList[ele.position + 1].left,
                                        top: this.defaultUserPositionList[ele.position + 1] && this.defaultUserPositionList[ele.position + 1].top,
                                    }
                                } else {
                                    return ele
                                }
                            })
                        }
                    } else if (_custom.type == 1) { //房间内管理员操作
                        console.log(_custom)
                        const { roomInfo } = _custom;
                        console.log('------------------------', _roomInfo);
                        let _roomInfo = JSON.parse(roomInfo);
                        this.roomInfo = _roomInfo;
                        _roomInfo.showGiftValue == true && this.giftValGet()
                    }

                }
            } else if (msg.attach.type == "updateQueue" || msg.attach.type == "batchUpdateQueue") {// 更新坑位上的用户信息
                const { queueChange } = msg.attach;
                const { elementKey, elementValue } = queueChange;
                if (queueChange.type == 'POLL') { //下麦
                    console.log('下麦')
                    this.$set(this.micQueue, this.micQueue.findIndex(item => item.position == elementKey), {
                        ...this.micQueue.find(item => item.position == elementKey),
                        avatar: '',
                        gender: '',
                        nick: '',
                        uid: '',
                        volume: 0
                    })

                    if (JSON.parse(elementValue).uid == this.identity.uid) {
                        await this.$api.downMic({
                            micUid: this.identity.uid,
                            position: elementKey,
                            roomUid: this.roomUid,
                        })
                        await new Promise((resolve) => {
                            agoraClient.muteLocal('audio', () => {
                                console.log('停止发送本地用户的音视频流成功');
                                agoraClient.unpublish(() => {
                                    console.log('unpublish-success');
                                    agoraClient.setRole('audience', () => {
                                        console.log('设置用户观众角色成功')
                                        resolve()
                                    })
                                }, (err) => { console.log(err) })
                            })
                        })


                    }
                } else if (queueChange.type == 'OFFER') {//上麦
                    console.log('上麦')
                    this.$set(this.micQueue, this.micQueue.findIndex(item => item.position == elementKey), {
                        ...this.micQueue.find(item => {
                            if (item.position == elementKey) {
                                item.left = this.defaultUserPositionList[item.position + 1] && this.defaultUserPositionList[item.position + 1].left
                                item.top = this.defaultUserPositionList[item.position + 1] && this.defaultUserPositionList[item.position + 1].top
                                return item
                            }
                            return undefined
                        }),
                        ...JSON.parse(elementValue),
                    })

                    //上麦
                    if (JSON.parse(elementValue).uid == this.identity.uid) {
                        await this.$api.upMic({
                            micUid: this.identity.uid,
                            position: elementKey,
                            roomUid: this.roomUid,
                        })
                        let curUser = this.micQueue.find(item => {
                            if (item.uid && this.identity.uid == item.uid) {
                                item.left = this.defaultUserPositionList[item.position + 1] && this.defaultUserPositionList[item.position + 1].left
                                item.top = this.defaultUserPositionList[item.position + 1] && this.defaultUserPositionList[item.position + 1].top
                                return item
                            }
                            return undefined
                        });
                        this.giftValGet()
                        await new Promise((reslove) => {
                            agoraClient.setRole('broadcaster', (res) => {
                                console.log('设置用户主播角色成功', res)
                                //恢复发送本地用户的音视频流成功
                                setTimeout(() => {
                                    if (curUser.micState == 1) {//设置静音
                                        console.log('位置设置了禁音')
                                        agoraClient.muteLocal('audio', () => {
                                            // this.stop()
                                            console.log('静音状态，已停止发送本地流')
                                            reslove()
                                        })
                                    } else {
                                        agoraClient.publish((url) => {
                                            this.pushUrl = url;
                                            console.log(this.pushUrl);
                                            setTimeout(() => {
                                                this.start();
                                                if (this.micFlag) {//判断用户本地静音状态
                                                    agoraClient.unmuteLocal('audio', () => {
                                                        console.log('恢复发送本地音频流成功');
                                                        reslove()
                                                    })
                                                } else {
                                                    agoraClient.muteLocal('audio', () => {
                                                        console.log('静音状态，已停止发送本地流')
                                                        reslove()
                                                    })
                                                }

                                            }, 500)

                                        })

                                    }
                                }, 500);

                            })
                        })
                    }
                } else if (queueChange.type == 'PARTCLEAR') {
                    console.log('用户离开房间')
                    this.$set(this.micQueue, this.micQueue.findIndex(item => item.uid == msg.attach.from), {
                        ...this.micQueue.find(item => item.uid == msg.attach.from),
                        avatar: '',
                        gender: '',
                        nick: '',
                        uid: '',
                        volume: 0
                    })
                }
                this.$forceUpdate()
            }
            this.checkRoomOwnerInPit()
        },


        //请求用户进入接口
        handleFetchUserIn() {
            const {
                roomId,
                pub_ticket,
                owner,
            } = this.roomParamsState;
            console.log('请求用户进入接口');
            const {
                uid
            } = this.identity;
            this.$api.userRoomIn({
                uid,
                roomUid: this.roomUid,
                pub_ticket
            }).then((res) => {
                this.isFavor = res.data.isFavor
            })
        },

        //发送云信聊天室信息
        confirm() {
            if (this.chatVal && this.chatVal.length > 0) {
                var msg = chatRoomInstance.sendText({
                    text: this.chatVal,
                    done: (error, msg) => {
                        console.log(msg);
                        msg.isMine = true,
                            this.chatVal = '';
                        this.chatMsgArr = [
                            ...this.chatMsgArr,
                            msg
                        ]
                        this.scrollTop += 100
                    }
                });
            } else {
                this.$interactive.toast('发送失败，内容不能为空')
            }

        },


        //刷新聊天室列表
        getChatroomMembers(guest) {
            chatRoomInstance.getChatroomMembers({
                guest,
                limit: 100,
                done: (error, obj) => {
                    this.memberList = [
                        this.mineChatMsg,
                        ...obj.members,
                    ];
                    console.log('-----------------------this.memberList', this.memberList);
                }
            });
        },

        //聊天室队列中获取列表
        getQueueList() {
            console.log('获取聊天室队列')
            chatRoomInstance.queueList({
                done: (err, obj, content) => {
                    if (err) {
                        console.error(err)
                    }
                    if (content && content.queueList) {
                        console.log('queueList', content.queueList)
                        for (let i = 0; i < content.queueList.length; i++) {
                            let queue = content.queueList[i];
                            this.$set(this.micQueue, this.micQueue.findIndex(ele => ele.position == Object.keys(queue)[0]), {
                                uid: '',
                                ...this.micQueue.find(item => {
                                    item.left = this.defaultUserPositionList[item.position + 1] && this.defaultUserPositionList[item.position + 1].left
                                    item.top = this.defaultUserPositionList[item.position + 1] && this.defaultUserPositionList[item.position + 1].top
                                    if (item.position == Object.keys(queue)[0]) {
                                        return item
                                    }
                                    return undefined
                                }),
                                ...JSON.parse(queue[Object.keys(queue)[0]]),
                            })
                            this.checkRoomOwnerInPit()
                        }
                        console.log(this.micQueue)
                    }
                }
            })
        },
        // 判断房主是否在坑位上
        checkRoomOwnerInPit() {
            let userArr = []
            this.micQueue.forEach(ele => {
                if (ele.uid) {
                    userArr.push(ele)
                }
            });
            let hasRoomParamsState = userArr.find(ele => ele.uid == this.roomUid)
            if (!hasRoomParamsState) {
                userArr.unshift(this.roomInfo)
            }
            // console.log('>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>userArr', userArr)
            this.userPositionList = userArr
        },

        throttle(cb, wait = 1000) {
            let last = 0;
            return function () {
                var now = new Date().getTime();;
                if (now - last > wait) {
                    cb.call(this);
                    last = new Date().getTime();;
                }
            }
        },

        async handleClickMic(item) {
            const fn = async () => {
                console.log('inini')
                const {
                    uid,
                } = this.identity;
                const { owner } = this.roomParamsState;
                let detailMsg = null;
                this.currentClickMicMsg = {
                    isMine: item.uid == uid,
                    msg: item,
                    detailMsg
                }
                if (item.uid) {// 麦位上有人在
                    await this.$api.roomUserGet({
                        uid,
                        roomUid: this.roomUid,
                        targetUid: item.uid,
                    }).then((res) => {
                        console.log(res);
                        detailMsg = res.data;
                        this.currentClickMicMsg.detailMsg = detailMsg;
                        this.open();
                    })
                } else {
                    if (this.currentInfo.role > 0) {
                        this.openManager()
                    } else {// 非房主点击麦位
                        console.log('移动位置')
                        if (item.posState == 1) {
                            uni.showToast({
                                title: '麦位已上锁',
                                icon: 'none'
                            });
                        } else if (item.position == '-1') {
                            uni.showToast({
                                title: '该位置仅房主/管理可上',
                                icon: 'none'
                            });
                        } else {
                            this.handleIntoPosition()
                        }

                    }
                }
            }
            if (this.timer) {
                clearTimeout(this.timer)
                this.timer = null;
            }
            if (timerFlag) {
                fn();
                timerFlag = false;
            } else {
                this.timer = setTimeout(function () {
                    fn()
                }, 800);
            }

        },

        handPollMic() {//抱他下麦
            const { msg } = this.currentClickMicMsg;
            const { avatar, nick, gender, position, uid } = msg;
            chatRoomInstance.queuePoll({
                elementKey: position,
                elementValue: JSON.stringify({
                    avatar,
                    gender,
                    nick,
                    uid,
                }),
                done: () => {
                    this.closeManager();
                    this.close();
                }
            })
        },

        handOfferQueen(item) {//点击用户列表中的某个人
            console.log(item)
            if (item.account == this.identity.uid) {//抱自己上麦
                this.handleIntoPosition()
            } else {
                chatRoomInstance.sendCustomMsg({
                    content: JSON.stringify({
                        data: {
                            handleUid: 0,
                            micPosition: this.currentClickMicMsg.msg.position,
                            uid: item.account,
                        },
                        first: 8,
                        second: 81
                    }),
                });
            }
            this.closePopupMembers()
        },

        openMebmerList() {//点击抱他上麦
            //获取聊天室列表
            this.getChatroomMembers(true);
            this.close();
            this.closeManager();
            this.openPopupMembers()
        },

        handSetMic() {//设置坑位麦克风
            let newMicQueue = {};
            for (let i = 0; i < this.micQueue.length; i++) {
                const _cur = this.micQueue[i];
                if (_cur.position == this.currentClickMicMsg.msg.position) {
                    newMicQueue[_cur.position] = JSON.stringify({
                        position: Number(_cur.position),
                        posState: Number(_cur.posState),
                        micState: Number(_cur.micState == 0 ? 1 : 0),
                    })
                } else {
                    newMicQueue[_cur.position] = JSON.stringify({
                        position: Number(_cur.position),
                        posState: Number(_cur.posState),
                        micState: Number(_cur.micState)
                    })
                }
            }

            chatRoomInstance.updateChatroom({
                chatroom: {
                    custom: JSON.stringify({
                        micQueue: JSON.stringify(newMicQueue),
                        roomInfo: JSON.stringify(this.roomInfo)
                    })
                },

                custom: JSON.stringify({
                    type: 2,
                    micInfo: newMicQueue[this.currentClickMicMsg.msg.position],

                }),
                needNotify: true,
                needSave: true,
                done: (error, obj) => {
                    this.closeManager();
                    this.close();
                    const _position = Number(this.currentClickMicMsg.msg.position) + 1
                    chatRoomInstance.sendCustomMsg({
                        content: JSON.stringify({
                            data: {
                                role: 0,
                                targetToast: this.currentClickMicMsg.msg.micState == 0 ? '当前麦位已关闭麦克风' : '当前锁麦已开放麦克风',
                                targetUid: 0,
                                tips: this.currentClickMicMsg.msg.micState == 0 ? `系统：管理员关闭了${_position}号麦位麦克风` : `系统：管理员解封了${_position}号麦位闭麦状态`
                            },
                            first: 20,
                            second: 204
                        }),
                    });
                }
            })
        },

        handSetLook() { //设置坑位锁定状态
            let newMicQueue = {};
            for (let i = 0; i < this.micQueue.length; i++) {
                const _cur = this.micQueue[i];
                if (_cur.position == this.currentClickMicMsg.msg.position) {
                    newMicQueue[_cur.position] = JSON.stringify({
                        position: Number(_cur.position),
                        posState: Number(_cur.posState == 0 ? 1 : 0),
                        micState: Number(_cur.micState),
                    })
                } else {
                    newMicQueue[_cur.position] = JSON.stringify({
                        position: Number(_cur.position),
                        posState: Number(_cur.posState),
                        micState: Number(_cur.micState)
                    })
                }
            }

            chatRoomInstance.updateChatroom({
                chatroom: {
                    custom: JSON.stringify({
                        micQueue: JSON.stringify(newMicQueue),
                        roomInfo: JSON.stringify(this.roomInfo)
                    })
                },

                custom: JSON.stringify({
                    type: 2,
                    micInfo: newMicQueue[this.currentClickMicMsg.msg.position],

                }),
                needNotify: true,
                needSave: true,
                done: (error, obj) => {
                    this.closeManager();
                    this.close();
                    const _position = Number(this.currentClickMicMsg.msg.position) + 1
                    chatRoomInstance.sendCustomMsg({
                        content: JSON.stringify({
                            data: {
                                role: 0,
                                targetToast: this.currentClickMicMsg.msg.posState == 0 ? '当前麦位已锁定' : '当前锁麦状态已解封',
                                targetUid: 0,
                                tips: this.currentClickMicMsg.msg.posState == 0 ? `系统：管理员锁定了${_position}号麦位` : `系统：管理员解封了${_position}号麦位`
                            },
                            first: 20,
                            second: 204
                        }),
                    });
                    //锁定状态下抱用户下麦
                    this.handPollMic()
                }
            })
        },

        async handleIntoPosition() {//管理员移动到此座位
            const {
                uid,
            } = this.identity;
            await new Promise((reslove) => {
                const currentUserMic = this.micQueue.find(i => i.uid == uid);
                if (currentUserMic) {//自己已经在某个座位上时
                    console.log('移除自己之前的座位');
                    const { nick, avatar, gender, position } = currentUserMic;
                    chatRoomInstance.queuePoll({
                        elementKey: position,
                        elementValue: JSON.stringify({
                            avatar,
                            gender,
                            nick,
                            uid,
                        }),
                        done(err, obj, content) {
                            reslove()
                        }
                    })
                } else {
                    reslove()
                }
            })
            const mine = this.memberList.find(each => each.account == uid);
            const { avatar, nick, account } = mine;
            const { gender } = JSON.parse(mine.custom)[account];
            chatRoomInstance.queueOffer({
                elementKey: this.currentClickMicMsg.msg.position,
                elementValue: JSON.stringify({
                    avatar,
                    gender,
                    nick,
                    uid
                }),
                transient: true,
                done(err, obj, content) {
                    if (err) {
                        console.error(err)
                    }
                }
            })
            this.closeManager();
            this.close()
        },

        handDisConnectMic() {
            console.log('下麦旁听');
            const {
                uid,
            } = this.identity;

            const currentUserMic = this.micQueue.find(i => i.uid == uid);
            console.log(currentUserMic);
            const { nick, avatar, gender, position } = currentUserMic;
            chatRoomInstance.queuePoll({
                elementKey: position,
                elementValue: JSON.stringify({
                    avatar,
                    gender,
                    nick,
                    uid,
                }),
                done: (err, obj, content) => {
                    this.closeManager();
                    this.close()
                }
            })
        },

        handFollowUser() {
            console.log(this.currentClickMicMsg)
            console.log('关注用户')
            this.$api.focusAdd({
                uid: this.identity.uid,
                likedUid: this.currentClickMicMsg.detailMsg.uid,
                ticket: this.tickets[0].ticket
            }).then(res => {
                if (res.code == 200) {
                    uni.showToast({
                        title: '关注成功',
                        icon: 'none'
                    })
                    this.currentClickMicMsg = {
                        ...this.currentClickMicMsg,
                        detailMsg: {
                            ...this.currentClickMicMsg.detailMsg,
                            focusStatus: 1
                        }
                    }
                }
            })
        },

        initAgora(roomId, uid) {
            agoraClient = new AgoraMiniappSDK.Client();
            agoraClient.init(this.$urlConfig.agoraKey, () => {
                console.log(String(roomId))
                // AgoraMiniappSDK.LOG.onlog = (text) => {
                //     Utils.log(text);
                // };
                // AgoraMiniappSDK.LOG.setLogLevel(-1);
                agoraClient.join(null, String(roomId), parseInt(uid), () => {
                    console.log('加入频道成功')
                    this.$interactive.hideLoading()
                    //订阅非自己的远程流
                    let micUsers = this.micQueue.filter(item => item.uid && item.micState == 0 && this.identity.uid != item.uid);
                    micUsers.forEach((item) => {
                        this.handleSubcribe(item.uid)
                    })

                    agoraClient.on("stream-added", e => { //通知应用程序已已添加远端音视频流
                        console.log('已添加远端音视频流', e);
                        this.handleSubcribe(e.uid)
                    });

                    agoraClient.on("stream-removed", e => { //通知应用程序已删除远端音视频流
                        console.log('已删除远端音视频流', e);
                        this.removeLiveSrcItem(e.uid)
                    });
                    agoraClient.on("mute-audio", e => { //通知应用程序远端用户已停止发送音频流。 该回调中会包含停止发送音频流的用户 ID。
                        console.log('远端用户已停止发送音频流', e);

                    });
                    agoraClient.on("unmute-audio", e => { //通知应用程序远端用户已恢复发送音频流。 该回调中会包含恢复发送音频流的用户 ID。
                        console.log('远端用户已恢复发送音频流', e)
                    });
                }, (err) => {
                    this.$interactive.hideLoading()
                    console.log('加入频道失败', err)
                })
            })

        },

        handleSubcribe(uid) { //订阅某个用户
            agoraClient.subscribe(Number(uid), res => {
                if (this.liveSrc.findIndex(item => item.uid == uid) == -1) { //地址里没有当前用户-- 添加
                    this.liveSrc.push({
                        uid: Number(uid),
                        url: res
                    })
                } else { //有的话修改地址
                    this.$set(this.liveSrc, this.liveSrc.findIndex(item => item.uid == uid), {
                        uid: Number(uid),
                        url: res
                    })
                }
                if (!this.voiceFlag) { //接收远端用户的音视频流。
                    this.liveSrc.forEach(({ uid }) => {
                        agoraClient.mute(uid, 'audio', () => {
                            console.log('停止接远端流成功')
                        })
                    })
                } else {
                    this.liveSrc.forEach(({ uid }) => {
                        agoraClient.unmute(uid, 'audio', () => {
                            console.log('恢复接远端流成功')
                        })
                    })
                }
            }, (err) => { console.log(err) }, { audio: true, video: false });
        },

        removeLiveSrcItem(uid) {
            console.log('删除这条流' + uid)
            this.liveSrc.findIndex(item => item.uid == uid) != -1 && this.liveSrc.splice(this.liveSrc.findIndex(item => item.uid == uid), 1);
            if (!this.voiceFlag) { //接收远端用户的音视频流。
                this.liveSrc.forEach(({ uid }) => {
                    agoraClient.mute(uid, 'audio', () => {
                        console.log('停止接远端流成功')
                    })
                })
            } else {
                this.liveSrc.forEach(({ uid }) => {
                    agoraClient.unmute(uid, 'audio', () => {
                        console.log('恢复接远端流成功')
                    })
                })
            }
        },


        handleIntoMsgDetail(item, open) {
            open && this.$refs.popup_p2pMsgs.open();
            nimInstance.setCurrSession(item.id)
            //滚动到底部
            nimInstance.getHistoryMsgs({
                scene: 'p2p',
                to: item.to,
                reverse: true,
                done: (err, obj) => {
                    this.detailMsgSession = {
                        ...obj,
                        mine: this.user,
                        other: item,
                        msgs: obj.msgs.map(msg => {
                            return {
                                ...msg,
                                mine: this.user,
                                other: item,
                                isMineFlag: msg.from == this.user.uid
                            }
                        }),
                        _curr: item
                    }
                    setTimeout(() => {
                        this.msgScrollTop = this.detailMsgSession.msgs.length * 80
                    }, 500);
                    console.log('------------------------------this.detailMsgSession', this.detailMsgSession.msgs.length)
                }
            });
            this.p2p_pop_type = 2;
        },

        handBackToP2PList() {
            console.log(this.detailMsgSession._curr.id)
            nimInstance.resetSessionUnread(this.detailMsgSession._curr.id)
            this.p2p_pop_type = 1;
            this.detailMsgSession = {};
            nimInstance.resetCurrSession();
        },
        sendP2PMsg() {
            console.log(this.p2pVal);
            if (this.p2pVal && this.p2pVal.length > 0) {
                nimInstance.sendText({
                    scene: 'p2p',
                    to: this.detailMsgSession.other.to,
                    text: this.p2pVal,
                    done: (error, msg) => {
                        //滚动到底部
                        this.p2pVal = ''
                        this.detailMsgSession.msgs.push({
                            ...msg,
                            mine: this.user,
                            other: this.detailMsgSession.other,
                            isMineFlag: true,
                        })
                        console.log(this.detailMsgSession)
                        this.msgScrollTop += 80
                    }
                });
            } else {
                this.$interactive.toast('发送失败，内容不能为空')
            }
        },

        changeVoiceFlag() {
            if (this.voiceFlag) { //停止接收远端用户的音视频流。
                this.liveSrc.forEach(({ uid }) => {
                    agoraClient.mute(uid, 'audio', () => {
                        console.log('停止接远端流成功')
                    })
                })
            } else {
                this.liveSrc.forEach(({ uid }) => {
                    agoraClient.unmute(uid, 'audio', () => {
                        console.log('恢复接远端流成功')
                    })
                })
            }
            this.voiceFlag = !this.voiceFlag;
        },

        changeMicFlag() {
            //    this.
            if (this.micFlag) { //判断本地是否开启了禁音
                agoraClient.muteLocal('audio', () => {
                    console.log('停止发送本地用户的音视频流成功');
                    // this.stop()
                })

            } else {
                const { uid } = this.identity;
                let _current = this.micQueue.find(item => item.uid == uid);
                console.log(_current)
                if (_current && _current.micState != 0) {
                    agoraClient.muteLocal('audio', () => {
                        console.log('停止发送本地用户的音视频流成功');
                    })
                    this.micFlag = !this.micFlag;
                    return
                }
                agoraClient.unmuteLocal('audio', () => {
                    console.log('恢复发送本地用户的音视频流成功');
                    this.start()
                })
            }
            this.micFlag = !this.micFlag;
        },

        giftValGet() {
            this.$api.valGet({
                roomUid: this.roomUid
            }).then((res) => {
                this.giftValueVos = res.data.giftValueVos
            })
        },

        statechange(e) {
            // console.log('推流state改变ononon')
            // console.log("statechange:" + e.detail.code);
        },
        netstatus(e) {
            // console.log("netstatus:" + JSON.stringify(e));
        },
        pusherError(e) {
            // console.log('ininininininini _____________________')
            // console.log("error:" + JSON.stringify(e));
        },
        stop: function () {
            return new Promise((reslove, reject) => {
                this.context.stop({
                    success: (a) => {
                        console.log(JSON.stringify(a));
                        reslove()
                    }
                });
            })

        },
        start: async function () {
            console.log(this)
            await this.stop();
            setTimeout(() => {
                this.context.start({
                    success: (a) => {
                        console.log("livePusher.start:" + JSON.stringify(a));
                    }
                }, 500);
            })

        },
        closePusher: function () {
            this.context.close({
                success: (a) => {
                    console.log("livePusher.close:" + JSON.stringify(a));
                }
            });
        },

        resume: function () {
            this.context.resume({
                success: (a) => {
                    console.log("livePusher.resume:" + JSON.stringify(a));
                }
            });
        },
        pause: function () {
            this.context.pause({
                success: (a) => {
                    console.log("livePusher.pause:" + JSON.stringify(a));
                }
            });
        },


        imageLoad(e) {
            // console.log('>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>', e)

        },
        // 一键全送
        sendAllGift() {
            let arr = []
            let selectGiveUserNum = 0
            this.userPositionList.forEach(ele => {
                if (ele.select) {
                    selectGiveUserNum++
                    arr.push(parseInt(ele.uid))
                }
            });
            this.selectUserArr = arr
            if (this.allGoldPrice == 0) {
                return this.$interactive.toast('背包无可送礼物')
            }
            if (selectGiveUserNum == 1) {
                this.$interactive.showModal(`确定一键送出所有背包礼物?\n
                    总价值：${this.allGoldPrice}`, () => {
                    let data = {
                        type: 3,
                        roomUid: this.roomUid,
                        targetUid: this.selectUserArr,
                        uid: this.identity.uid,
                    }
                    this.$apiQjc.sendBackpackAllIn(data).then(res => {
                        if (res.code == 200) {
                            // 更新钱包
                            this.getWallet()
                            let giftContent = {
                                first: 3,
                                second: 31,
                                data: res.data,
                            }
                            giftContent.data = res.data

                            if (this.titleActiveIndex == 3) {
                                // 更新背包
                                this.getUserBackpack()
                            }
                            this.initGiftData(giftContent, 'all')
                            console.log('--------------------------------------------------------------', giftContent);
                            // 更新礼物值
                            this.updateGiftValue(this.selectUserArr)
                        }
                    })
                })
            } else if (selectGiveUserNum == 0) {
                this.$interactive.toast('请选择要礼的对象')
            } else {
                return this.$interactive.toast('只能选择送给某一个人')
            }
        },
        // 送礼接口
        sendGift() {
            // sendType: 1房间不在麦位上的送礼，2 私聊送礼,3给房间麦位用户送礼
            // giftSource:1 购买；2 背包
            let arr = []
            let selectGiveUserNum = 0

            if (this.currentSelctGive) {
                if (this.titleActiveIndex == 3 && this.currentSelctGive.count < this.currentGiveSelectData.num) {
                    return this.$interactive.toast('背包礼物数量不足')
                } else if (this.goldNum < this.currentSelctGive.goldPrice * this.currentGiveSelectData.num) {
                    return this.$interactive.toast('余额不足')
                }
                this.userPositionList.forEach(ele => {
                    if (ele.select) {
                        selectGiveUserNum++
                        arr.push(parseInt(ele.uid))
                    }
                });
                this.selectUserArr = arr
                if (selectGiveUserNum == 0) {
                    this.$interactive.toast('请选择要礼的对象')
                } else {
                    if (selectGiveUserNum == this.userPositionList.length) {
                        this.giftContentFirst = 12
                    } else {
                        this.giftContentFirst = 3
                    }
                    let second = ''
                    if (this.giftContentFirst == 3) {
                        // 单人
                        switch (this.titleActiveIndex) {
                            case 0:
                                // 福袋
                                second = 33
                                break;
                            case 1:
                                // 活动
                                second = 31
                                break;
                            case 2:
                                // 送礼
                                second = 31
                                break;
                            case 3:
                                // 背包
                                second = 31
                                break;
                            case 4:
                                // 特权
                                second = 38
                                break;
                        }
                    }
                    else {
                        // 全麦送礼
                        switch (this.titleActiveIndex) {
                            case 0:
                                // 福袋
                                second = 122
                                break;
                            case 1:
                                // 活动
                                second = 121
                                break;
                            case 2:
                                // 送礼
                                second = 121
                                break;
                            case 3:
                                // 背包
                                second = 121
                                break;
                            case 4:
                                // 特权
                                this.giftContentFirst = 3
                                second = 38
                                break;
                        }
                    }
                    let data = {
                        giftId: this.currentSelctGive.giftId,
                        giftNum: this.currentGiveSelectData.num,
                        giftSource: this.titleActiveIndex == 3 ? 2 : 1,
                        sendType: 3,
                        roomUid: this.roomUid,
                        targetUids: this.selectUserArr,
                        uid: this.identity.uid,
                    }
                    this.$apiQjc.sendGift(data).then(res => {
                        if (res.code == 200) {
                            // 更新钱包
                            this.getWallet()
                            let giftContent = {
                                first: this.giftContentFirst,
                                second: second,
                                // data: this.titleActiveIndex == 0 ? { luckyGiftList: res.data } : res.data[0],
                            }
                            if (this.titleActiveIndex == 0 && this.giveAll) {
                                giftContent.data = { luckyGiftList: res.data }
                                console.log('----------------------------------全麦福袋送礼msg', giftContent);
                                this.initGiftData(giftContent)
                            } else {
                                if (res.data.length > 0) {
                                    res.data.forEach((dele, dindex) => {
                                        giftContent.data = dele
                                        // giftContent.data.targetNick = dele.receivers[dindex].nick
                                        if (this.titleActiveIndex == 3) {
                                            this.getUserBackpack('update')
                                        } else if (this.titleActiveIndex == 4) {
                                            this.getRoomVipCardList()
                                        }
                                        this.initGiftData(giftContent)
                                    });
                                }
                            }

                            this.updateGiftValue(this.selectUserArr)
                            // if (this.titleActiveIndex == 3) {
                            //     this.getUserBackpack('update')
                            // } else if (this.titleActiveIndex == 4) {
                            //     this.getRoomVipCardList()
                            // }
                            // this.initGiftData(giftContent)
                            // this.updateGiftValue(this.selectUserArr)
                            // this.giftValGet()

                        }
                    })
                }
            } else {
                this.$interactive.toast('请先选择要送出的礼物')
            }

        },
        initGiftData(msgContent, sendType) {
            console.log('----------------------------------送礼msg', msgContent);
            let giftData = msgContent.data
            if (giftData.giftInfoVos && giftData.giftInfoVos.length > 0) {

                giftData.giftInfoVos.forEach(infoEle => {
                    giftData.giftId = infoEle.giftId
                    giftData.giftNum = infoEle.giftNum
                    giftData.giftUrl = infoEle.gift.giftUrl
                    giftData.gift = infoEle.gift
                    console.log('----------------------------------一件送礼送礼msg', msgContent);
                    let data = {
                        first: 3, second: 31,
                        data: giftData
                    }
                    chatRoomInstance.sendCustomMsg({
                        content: JSON.stringify(data),
                        done: (error, msg) => {
                            this.chatMsgArr = [
                                ...this.chatMsgArr,
                                msg
                            ]
                            this.scrollTop += 50
                        }
                    });
                    this.addAnimation([giftData.targetUid], infoEle.gift.giftUrl)
                });
            } else if (giftData.luckyGiftList && giftData.luckyGiftList.length > 0) {
                console.log('11111111111111111111111111111福袋');
                giftData.luckyGiftList.forEach((luckyGiftEle, index) => {
                    // 福袋爆出的礼物
                    let luckyBagGift = this.allLuckyGiftList.find(ele => ele.giftId == luckyGiftEle.giftId)
                    luckyGiftEle.giftUrl = luckyBagGift && luckyBagGift.giftUrl
                    luckyGiftEle.goldPrice = luckyBagGift.goldPrice
                    let data = {
                        first: msgContent.first,
                        second: msgContent.second,
                        data: {
                            luckyGiftList: [luckyGiftEle]
                        }
                    }
                    // 福袋爆出的礼物
                    if (index == 0) {

                        chatRoomInstance.sendCustomMsg({
                            content: JSON.stringify(data),
                            done: (error, msg) => {

                                this.addAnimation(luckyGiftEle.targetUids, luckyGiftEle.giftUrl)
                                msg.content = JSON.stringify(msgContent)
                                this.chatMsgArr = [
                                    ...this.chatMsgArr,
                                    msg
                                ]
                                this.scrollTop += 50
                            }
                        });
                    }
                });
                // giftData.luckyGiftList.forEach((luckyGiftEle, index) => {
                //     // 福袋爆出的礼物
                //     let luckyBagGift = this.allLuckyGiftList.find(ele => ele.giftId == luckyGiftEle.giftId)
                //     luckyGiftEle.giftUrl = luckyBagGift && luckyBagGift.giftUrl
                //     luckyGiftEle.goldPrice = luckyBagGift.goldPrice
                //     this.addAnimation(luckyGiftEle.targetUids, luckyGiftEle.giftUrl)
                // });
            } else {
                // chatRoomInstance.sendCustomMsg({
                //     content: JSON.stringify(msgContent),
                //     done: (error, msg) => {
                //         giftData.giftUrl = giftData.gift && giftData.gift.giftUrl
                //         this.addAnimation(giftData.targetUids || [giftData.targetUid], giftData.giftUrl)
                //         msg.content = JSON.stringify(msgContent)
                //         this.chatMsgArr = [
                //             ...this.chatMsgArr,
                //             msg
                //         ]
                //         this.scrollTop += 50
                //     }
                // });
                // 非全麦普通送礼
                if (giftData.targetUids.length > 1 && giftData.targetUids.length < this.userPositionList.length) {
                    giftData.targetUids.forEach((ele, index) => {
                        giftData.targetNick = giftData.receivers[index].nick
                        let data = {
                            first: msgContent.first,
                            second: msgContent.second,
                            data: giftData
                        }
                        chatRoomInstance.sendCustomMsg({
                            content: JSON.stringify(data),
                            done: (error, msg) => {



                                // msg.content = JSON.stringify(data)
                                this.chatMsgArr = [
                                    ...this.chatMsgArr,
                                    msg
                                ]
                                this.scrollTop += 50
                            }
                        });
                    });
                    giftData.giftUrl = giftData.gift && giftData.gift.giftUrl
                    this.addAnimation(giftData.targetUids || [giftData.targetUid], giftData.giftUrl)
                } else {
                    console.log('///////////////////////单人或全麦', giftData.targetNick);
                    chatRoomInstance.sendCustomMsg({
                        content: JSON.stringify(msgContent),
                        done: (error, msg) => {
                            giftData.giftUrl = giftData.gift && giftData.gift.giftUrl
                            let data = {
                                first: msgContent.first,
                                second: msgContent.second,
                                data: giftData
                            }
                            this.addAnimation(giftData.targetUids || [giftData.targetUid], giftData.giftUrl)
                            msg.content = JSON.stringify(data)
                            this.chatMsgArr = [
                                ...this.chatMsgArr,
                                msg
                            ]
                            this.scrollTop += 50
                        }
                    });
                }
            }
            // chatRoomInstance.sendCustomMsg({
            //     content: JSON.stringify(msgContent),
            //     done: (error, msg) => {
            //         let giftData = msgContent.data
            //         if (giftData.luckyGiftList && giftData.luckyGiftList.length > 0) {
            //             giftData.luckyGiftList.forEach((luckyGiftEle, index) => {
            //                 // 福袋爆出的礼物
            //                 let luckyBagGift = this.allLuckyGiftList.find(ele => ele.giftId == luckyGiftEle.giftId)
            //                 luckyGiftEle.giftUrl = luckyBagGift && luckyBagGift.giftUrl
            //                 luckyGiftEle.goldPrice = luckyBagGift.goldPrice
            //                 this.addAnimation(luckyGiftEle.targetUids, luckyGiftEle.giftUrl)
            //             });
            //         } else {

            //             if (giftData.giftInfoVos && giftData.giftInfoVos.length > 0) {
            //                 giftData.giftInfoVos.forEach(infoEle => {
            //                     infoEle.giftUrl = infoEle.gift && infoEle.gift.giftUrl
            //                     this.addAnimation([giftData.targetUid], infoEle.giftUrl)
            //                 });
            //             } else {
            //                 giftData.giftUrl = giftData.gift && giftData.gift.giftUrl
            //                 this.addAnimation(giftData.targetUids || [giftData.targetUid], giftData.giftUrl)
            //             }
            //         }

            //         msg.content = JSON.stringify(msgContent)
            //         this.chatMsgArr = [
            //             ...this.chatMsgArr,
            //             msg
            //         ]
            //         this.scrollTop += 50
            //     }
            // });
        },
        updateGiftValue(selectUserArr) {
            let data = {
                roomUid: this.roomUid,
                targetUids: selectUserArr.join(',')
            }
            this.$apiQjc.getUserGiftValue(data).then(res => {
                console.log(res);
                if (res.code == 200) {
                    let giftContent = {
                        first: 42,
                        second: 421,
                        data: {
                            roomGiftValue: res.data
                        },
                    }
                    chatRoomInstance.sendCustomMsg({
                        content: JSON.stringify(giftContent),
                        done: (error, msg) => {
                            this.giftValGet()
                        }
                    });
                    // this.allLuckyGiftList = res.data
                }
            })
        },
        // 送礼动画
        addAnimation(targetUids, giftUrl) {
            targetUids && targetUids.forEach(tuid => {
                // 送礼没在麦位的给房主
                if (tuid == this.roomUid) {
                    let animation = wx.createAnimation({
                        duration: 1500,
                        timingFunction: 'ease'
                    })
                    let animationItem = animation.top(this.giftBoxTop).scale(8, 8).step()
                        .scale(10, 10).step()
                        .scale(2, 2).left(150).top(40).step()
                        .opacity(0).step({ duration: 10 }).export()
                    // 送礼图片
                    this.giveAnimationList.push({ giftUrl: giftUrl })
                    setTimeout(() => {
                        // 送礼动画对象
                        this.giveAnimationList2.push(animationItem)
                    }, 50);

                    if (this.giftAnimationTimer) {
                        clearTimeout(this.giftAnimationTimer)
                        this.giftAnimationTimer = null
                    }
                    this.giftAnimationTimer = setTimeout(() => {
                        this.giveAnimationList2 = []
                        this.giveAnimationList = []
                    }, 3000);
                } else {
                    this.userPositionList.forEach(ele => {
                        if (tuid == ele.uid) {
                            console.log('--------------------------tuid', targetUids, giftUrl)
                            let animation = wx.createAnimation({
                                duration: 1500,
                                timingFunction: 'ease'
                            })
                            let animationItem = animation.top(this.giftBoxTop).scale(8, 8).step()
                                .scale(10, 10).step()
                                .scale(2, 2).left(ele.left).top(ele.top).step()
                                .opacity(0).step({ duration: 10 }).export()
                            // 送礼图片
                            this.giveAnimationList.push({ giftUrl: giftUrl })
                            setTimeout(() => {
                                // 送礼动画对象
                                console.log('>>>>>>>>>>>>>>>>>>>>>>>>>>>>执行动画')
                                this.giveAnimationList2.push(animationItem)
                            }, 50);

                            if (this.giftAnimationTimer) {
                                clearTimeout(this.giftAnimationTimer)
                                this.giftAnimationTimer = null
                            }
                            this.giftAnimationTimer = setTimeout(() => {
                                this.giveAnimationList2 = []
                                this.giveAnimationList = []
                            }, 3000);
                        }
                    })
                }
            });
        },
        getRpx(num) {
            // console.log('>>>>>>>>>>>>>>>>>>>>>', (750 / this.windowWidth) * num)
            return (750 / this.windowWidth) * num
        },
        // 点击礼物/背包等菜单栏
        changeTitleActiveIndex(index) {
            this.titleActiveIndex = index
            this.currentSelctGive = null
            this.giftActiveIndex = -1
        },
        // 点击礼物
        changeGiftActiveIndex(item, index) {
            this.currentSelctGive = item
            this.giftActiveIndex = index
        },
        // 获取礼物列表
        getGiftList() {
            this.$api.getGiftList({}).then(res => {
                let objTmp = new Map()
                let activityGiftArr = []
                if (res.code == 200) {
                    res.data.gift.forEach(ele => {
                        // giftType，1:普通礼物，3:福袋；6:转盘礼物；7:新人礼物
                        if (ele.activityGift) {
                            activityGiftArr.push(ele)
                        } else {
                            if (objTmp.has(ele.giftType)) {
                                let arr = objTmp.get(ele.giftType)
                                arr.push(ele)
                                objTmp.set(ele.giftType, arr)
                            } else {
                                objTmp.set(ele.giftType, [ele])
                            }
                        }
                    })

                    this.giftList[0] = objTmp.get(3)
                    this.giftList[1] = activityGiftArr
                    this.giftList[2] = objTmp.get(1)
                }
            })
        },
        invalidGifts() {
            this.$apiQjc.invalidGifts({}).then(res => {
                console.log(res);
                if (res.code == 200) {
                    this.allLuckyGiftList = res.data
                }
            })
        },
        // 获取用户背包
        getUserBackpack(update) {
            this.$api.listUserBackpackV2({
                uid: this.identity.uid
            }).then(res => {
                console.log(res);
                if (res.code == 200) {
                    // 当前背包礼物数量已送完
                    this.allGoldPrice = res.data.allGoldPrice
                    this.giftList[3] = res.data.userBackpackVos
                    console.log('-**********************,更新背包 ', update, this.currentSelctGive && this.currentSelctGive.count)
                    if (update == 'update' && this.currentSelctGive.count < 2) {
                        this.giftActiveIndex = -1
                        this.currentSelctGive = null
                    } else {
                        this.currentSelctGive = res.data.userBackpackVos[this.giftActiveIndex]
                    }
                }
            })
        },
        // 获取贵宾卡
        getRoomVipCardList() {
            const { owner } = this.roomParamsState;
            this.$apiQjc.userRoomVipCardList({
                uid: this.identity.uid,
                roomUid: this.roomUid,
            }).then(res => {
                console.log(res);
                if (res.code == 200) {
                    this.giftList[4] = res.data
                }
            })
        },
        /* 获取我的钱包 */
        getWallet() {
            this.$api.getWallet({
                uid: this.identity.uid
            }).then(res => {
                console.log(res);
                if (res.code == 200) {
                    this.goldNum = res.data.goldNum;
                }
            })
        },
        // 去充值
        gotoRecharge() {
            uni.navigateTo({
                url: '/pages/wallet/recharge/recharge'
            });
        },
        // 点击礼物
        changeGiveSelect(item, index) {
            this.currentGiveSelectData = item
        },
        // 弹出礼物框
        showGiftModel() {
            this.$refs.giftPopup.open()
            setTimeout(() => {
                const query = uni.createSelectorQuery().in(this);
                query.select(`.gift_box`).boundingClientRect(data => {
                    this.giftBoxTop = data.top - 30
                }).exec()
            }, 500);
        },
        showManagePopup() {
            this.$refs.popupManager.open()
        },
        closeManagePopup() {
            this.$refs.popupManager.close()
        },
        onConfirmPsd() {
            // console.log(this.insertPsd)
            const { role } = this.currentInfo;
            // console.log(role)
            // if (role == 1 || role == 2) { //管理员设置密码
            //     this.$api.updateByAdmin({
            //         roomPwd: des_encrypt(this.insertPsd)
            //     }).then(res => {
            //         console.log(res)
            //         if (res.code == 200) {
            //             this.onConnect()
            //         } else {
            //             this.$interactive.toast('操作失败')
            //         }
            //     })
            // } else if (role == 3) {//房主设置密码
            //     this.$api.roomUpdate({
            //         roomPwd: des_encrypt(this.insertPsd)
            //     }).then(res => {
            //         console.log(res)
            //         if (res.code == 200) {
            //             this.onConnect()
            //         } else {
            //             this.$interactive.toast('操作失败')
            //         }
            //     })
            // }
            if (role == 3) {//房主设置密码
                this.$api.roomUpdate({
                    ...this.roomInfo,
                    roomPwd: des_encrypt(this.insertPsd)
                }).then(res => {
                    console.log(res)
                    if (res.code == 200) {
                        this.$interactive.toast('设置密码成功')
                        this.onConnect()
                    } else {
                        this.$interactive.toast('操作失败')
                    }
                })
            } else {
                this.$interactive.toast('暂无权限！')
            }
            this.$refs.insertPsd.close()
        },
        editPsd() {
            this.$refs.editPsd.close()
            this.$refs.insertPsd.open()
        },
        closePsd() {
            const { role } = this.currentInfo;
            if (role == 3) {//房主设置密码
                this.$api.roomUpdate({
                    ...this.roomInfo,
                    roomPwd: ''
                }).then(res => {
                    console.log(res)
                    if (res.code == 200) {
                        this.$interactive.toast('房间解锁成功')
                        this.onConnect()
                    } else {
                        this.$interactive.toast('操作失败')
                    }
                })
            } else {
                this.$interactive.toast('暂无权限！')
            }
            this.$refs.editPsd.close()
        },
        handleEnterPsd() {
            // console.log(this.roomInfo.psdw)
            const { roomPwd } = this.roomInfo;

            console.log(roomPwd, des_encrypt(this.enterPsd))
            if (roomPwd == des_encrypt(this.enterPsd)) {
                this.$refs.enterPsd.close()
                this.psdResolve();
            } else {
                this.$interactive.toast('密码错误！')
            }
            //  this.psdResolve
        },
        changeItem(item, index) {
            // 这个控制状态
            // item.type,true：开，false：关
            if (this.currentInfo.role == 1 || this.currentInfo.role == 2 || this.currentInfo.role == 3) {
                let text = ''
                if (index == 0) text = `确认${item.type ? '解' : '上'}锁房间吗`
                if (index == 1) text = `确认${item.type ? '关闭' : '开启'}锁礼物值吗`
                if (index == 2) text = `确认${item.type ? '开启' : '关闭'}公屏吗`
                if (index == 3) text = `确认${item.type ? '清空' : '清空'}公屏吗`

                this.$interactive.showModal(text, () => {
                    switch (index) {
                        case 0:
                            console.log(item.type)
                            this.closeManagePopup()
                            if (!item.type) {
                                this.$refs.insertPsd.open()
                            } else {
                                this.$refs.editPsd.open()
                            }
                            break;
                        case 1:
                            if (!item.type) {
                                this.$apiQjc.openRoomGift({
                                    roomUid: this.roomUid,
                                }).then(res => {
                                    if (res.code == 200) {
                                        this.onConnect()
                                        this.$interactive.toast('操作成功')
                                    } else {
                                        this.$interactive.toast('操作失败')
                                    }
                                })
                            } else {
                                this.$apiQjc.closeRoomGift({
                                    roomUid: this.roomUid,
                                }).then(res => {
                                    if (res.code == 200) {
                                        this.onConnect()
                                        this.$interactive.toast('操作成功')
                                    } else {
                                        this.$interactive.toast('操作失败')
                                    }
                                })
                            }
                            break;
                        case 2:
                            this.$apiQjc.setCloseScreen({
                                isCloseScreen: !item.type,
                                roomId: this.roomInfo.roomId,
                                uid: this.roomUid
                            }).then(res => {
                                if (res.code == 200) {
                                    this.onConnect()
                                    this.$interactive.toast('操作成功')
                                } else {
                                    this.$interactive.toast('操作失败')
                                }
                            })
                            break;
                        case 3:
                            console.log('ininin')
                            this.$api.cleanScreen({
                                roomId: this.roomInfo.roomId
                            }).then((res) => {
                                let newMicQueue = {};
                                for (let i = 0; i < this.micQueue.length; i++) {
                                    const _cur = this.micQueue[i];

                                    newMicQueue[_cur.position] = JSON.stringify({
                                        position: Number(_cur.position),
                                        posState: Number(_cur.posState),
                                        micState: Number(_cur.micState)
                                    })

                                }

                                chatRoomInstance.updateChatroom({
                                    chatroom: {
                                        custom: JSON.stringify({
                                            micQueue: JSON.stringify(newMicQueue),
                                            roomInfo: JSON.stringify({
                                                ...this.roomInfo,
                                                cleanScreenTime: new Date().getTime()
                                            })
                                        })
                                    },
                                    needNotify: true,
                                    needSave: true,
                                })
                                this.closeManagePopup()

                            })
                            break;
                    }
                });
            } else {
                this.$interactive.toast('您无操作权限！')
            }
        },
        changeUserSelect(item, index) {
            item.select = !item.select
            this.$set(this.userPositionList, index, item)
        },
        // 切换全麦
        changeGiveUser() {
            this.giveAll = !this.giveAll
            if (this.giveAll) {
                this.userPositionList.forEach(ele => {
                    ele.select = true
                });
            } else {
                this.userPositionList.forEach(ele => {
                    ele.select = false
                });
            }

        },
        // 初始化各麦位坐标点
        initUserPosition() {
            let arr = []
            var query = uni.createSelectorQuery().in(this);
            for (let index = -1; index < 8; index++) {
                query.select(`#userPosition${index}`).boundingClientRect()
            }
            query.exec((res) => {
                res.forEach(ele => {
                    // 取中心点
                    let userPositionItem = {
                        left: ele.left + 28,
                        top: ele.top + 28,
                    }
                    arr.push(userPositionItem)
                });
            })
            this.defaultUserPositionList = arr
        },

    }
}
</script>

<style lang="scss">
@import "./index.scss";
</style>
